leak in fgets when assigning to buffer

Posted by monkeyking on Stack Overflow See other posts from Stack Overflow or by monkeyking
Published on 2010-05-13T08:13:09Z Indexed on 2010/05/13 8:24 UTC
Read the original article Hit count: 259

Filed under:
|
|

I'm having problems understanding why following code leaks in one case, and not in the other case. 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.

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);  


}

© Stack Overflow or respective owner

Related posts about c

    Related posts about fgets