Search code examples
cstringnullfgets

memory allocate string for fgets with null terminating char


I'm really sorry if this question seems "easy" but I couldn't find an answer anywhere. I tried to use fgets() to read a line from a file. To make sure no space was wasted, first of all I found the line's length:

do
    {
        c= getc(file);
        words++;
    }while (c!=EOF && c!='\n');

then I allocated memory for exacly the number of words:

char* line = (char*)malloc(sizeof(char)*(words));

and then, I use fgets() to read the line to the line buffer. But the problem is, this is working. But I always thought you should allocate memory for the null terminating char too. So what happened here?


Solution

  • You do need to allocate space for the null terminator. The fact that this is working doesn't mean it always will (at least in C).

    Plus, fgets also returns the \n character. So you will need two extra characters. One for \n and one for \0.

    I would recommend this approach though:

    char buffer [1024];
    if ( fgets (buffer, 1024, f) != NULL ) {
       // so something with buffer
    }