Reputation: 1
Can you guys help me to identify where is the memory leak?
void foo(char *name){
char * p = (char *)malloc(1024);
char * buf = (char *)malloc(1024);
sprintf(p, "User name: %s", name);
printf("Format string is %s\n", p);
buf = p;
free(p);
free(buf);
}
Upvotes: 0
Views: 68
Reputation: 16540
this is the memory leak:
buf = p;
because it overlays one of the pointers to allocated memory.
However, due to the above statement, this statement:
free(buf);
will cause a program crash because the memory pointed to be buf
has already been passed to free()
so, two bad things in the posted code.
To fix it all, remove this statement:
buf = p;
Upvotes: 0
Reputation: 385847
p
initially points to BLOCK1.buf
initially points to BLOCK2.buf
is changed to point to BLOCK1 (buf = p;
). Nothing points to BLOCK2 now. Memory leak.free(p)
), but you never free BLOCK2.Also, you invoke undefined behaviour by attempting to free a block that has already been freed (free(buf)
).
If you are trying to copy the string, strncpy
or strcpy
should be used in lieu of buf = p;
.
If you are trying to copy the pointer, only allocate one block (using char *buf = p;
in lieu of char *buf = malloc(...); buf = p;
).
Upvotes: 3