Path: csiph.com!usenet.pasdenom.info!aioe.org!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: Method other than strlen to check for truncation with fgets? Date: Thu, 07 May 2015 12:00:01 -0700 Organization: None to speak of Lines: 37 Message-ID: <878ud0jjri.fsf@kst-u.example.com> References: Mime-Version: 1.0 Content-Type: text/plain Injection-Info: mx02.eternal-september.org; posting-host="9be37d943435275679235b07c7947eef"; logging-data="31369"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/pMN7JKELrh+9sAq2sVkLH" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/24.3 (gnu/linux) Cancel-Lock: sha1:2y7KEIFRbVjnJ9okBhDzhk1d2W4= sha1:25dK3p58VRO9USw/bheDkz9ZvsI= Xref: csiph.com comp.lang.c:61712 Siri Cruz writes: > In article , mathog wrote: >> It should work when the input line is truncated. The problem is that, >> from my reading of the fgets man page, there is no guarantee that the >> library will not write something beyond the \0 in the buffer. I don't >> expect that would happen, but also do not see anything saying that it >> cannot. > > If this is critical to you, use fgetline instead. > > /* > Read and return the next line from input. > The line is mallocked; caller is responsibile for freeing. > The line ends in \n if the line from the input file did. > Returns NULL on EOF. > */ > > char *fgetline (FILE *input) { > int c; char *line = NULL; int m = 0, n = 0; > while ((c=fgetc(input))!=EOF) { > if (c==0) abort(); > if (n+1>=m) {m = 2*(n+1); line = realloc(line, m);} > if (!line) abort(); > line[n++] = c; > if (c=='\n') break; > } > if (line) {line = realloc(line, n+1); line[n] = 0;} > return line; > } This doesn't check for allocation failures. -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"