Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does fscanf allocate memory and place a NUL byte at the end of a string?

Tags:

c

scanf

If I am correct, doing something like:

char *line;

Then I must allocate some memory and assign it to line, is that right? If I am right, the question is the following:

In a line like

while (fscanf(fp,"%[^\n]", line) == 1) { ... } 

without assigning any memory to line I am still getting the correct lines and the correct strlen counts on such lines.

So, does fscanf assign that memory for me and it also places the '\0'? I saw no mention about these 2 things on the spec for fscanf.

like image 941
SJPRO Avatar asked Nov 29 '22 10:11

SJPRO


1 Answers

The POSIX scanf() family of functions will allocate memory if you use the m (a on some older pre-POSIX versions) format modifier. Note: when fscanf allocates, it expects a char ** pointer. (see man scanf) E.g.:

while(fscanf(fp,"%m[^\n]", &line) == 1) { ... }

I would also suggest consuming the newline with "%m[^\n]%*c". I agree with the other answers that suggest using line-oriented input instead of fscanf. (e.g. getline -- see: Basile's answer)

like image 145
David C. Rankin Avatar answered Dec 05 '22 06:12

David C. Rankin