Leak in fgets when assigning a buffer

I am having trouble understanding why a code leak occurs in one case and not in another. The difference is

while(NULL!=fgets(buffer,length,file))//doesnt leak while(NULL!=(buffer=fgets(buffer,length,file))//leaks 

I thought it would be the same thing.

Full code below.

 #include <stdio.h> #include <stdlib.h> #define LENS 10000 void no_leak(const char* argv){ char *buffer = (char *) malloc(LENS); FILE *fp=fopen(argv,"r"); while(NULL!=fgets(buffer,LENS,fp)){ fprintf(stderr,"%s",buffer); } fclose(fp); fprintf(stderr,"%s\n",buffer); free(buffer); } void with_leak(const char* argv){ char *buffer = (char *) malloc(LENS); FILE *fp=fopen(argv,"r"); while(NULL!=(buffer=fgets(buffer,LENS,fp))){ fprintf(stderr,"%s",buffer); } fclose(fp); fprintf(stderr,"%s\n",buffer); free(buffer); } 
+4
source share
4 answers

Because you reassign which buffer you pointed to. When you get to free(buffer); at the end of the code, the buffer will point to NULL (because this is what you tested to exit the while loop), and therefore, when you call for free, you are not calling it on the original malloc pointer, you donโ€™t have anything call.

+7
source

If fgets() returns NULL , buffer loses its original value, so you cannot free it.

+2
source

Successfully reading this will be good. But when the end of the file is reached, fgets will return NULL, and thus the buffer will be NULL, and you will not be able to free it.

+1
source

You will get a leak when fgets returns NULL. It is legal to call NULL for free, but of course, at this point you have lost your original pointer.

+1
source

Source: https://habr.com/ru/post/1309636/


All Articles