diff --git a/parse.c b/parse.c
index e68627c..947dbb8 100644
--- a/parse.c
+++ b/parse.c
@@ -118,6 +118,10 @@ ldns_fget_token_l(FILE *f, char *token, const char *delim, size_t limit, int *li
 			if (line_nr) {
 				*line_nr = *line_nr + 1;
 			}
+			if (limit > 0 && (i >= limit || (size_t)(t-token) >= limit)) {
+				*t = '\0';
+				return -1;
+			}
 			*t++ = ' ';
 			prev_c = c;
			continue;
