Reputation: 333
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?
Upvotes: 1
Views: 1379
Reputation: 93708
Its working by pure luck. Writing past the end of allocated memory is undefined behavior. It isn't an instant crash. It may crash instantly, or later on down the line, or it may work just fine. It all depends on how big the overwrite is and what the memory immediately after is used for. It will frequently be padding or currently unused space, and thus just work. You can't count on that though. The correct answer is to malloc 2 more characters than needed (1 for the terminator and 1 for the \n that fgets will copy).
Upvotes: 1
Reputation: 181460
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
}
Upvotes: 5