Reputation: 13
I'm just learning C and don't understand why this little piece of code causes a memory leak:
mem_ptr=(char*)malloc(24);
if (mem_ptr == NULL){
exit(EXIT_FAILURE);
}
mem_ptr="TEST";
printf("%s\n",mem_ptr);
free(mem_ptr);
When I run it, Valgrind tells me:
==17900== Invalid free() / delete / delete[] / realloc()
==17900== at 0x4C2B75D: free (vg_replace_malloc.c:468)
==17900== by 0x40086F: main (main.c:69)
==17900== Address 0x40099f is not stack'd, malloc'd or (recently) free'd
==17900==
==17900==
==17900== HEAP SUMMARY:
==17900== in use at exit: 24 bytes in 1 blocks
==17900== total heap usage: 1 allocs, 1 frees, 24 bytes allocated
==17900==
==17900== LEAK SUMMARY:
==17900== definitely lost: 24 bytes in 1 blocks
==17900== indirectly lost: 0 bytes in 0 blocks
==17900== possibly lost: 0 bytes in 0 blocks
==17900== still reachable: 0 bytes in 0 blocks
==17900== suppressed: 0 bytes in 0 blocks
==17900== Rerun with --leak-check=full to see details of leaked memory
==17900==
==17900== For counts of detected and suppressed errors, rerun with: -v
==17900== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Upvotes: 0
Views: 761
Reputation: 754920
You missed a strcpy()
:
mem_ptr=(char*)malloc(24);
mem_ptr="TEST";
This threw away the only pointer to the allocated space. When you tried to free "TEST"
then valgrind
complained that it wasn't allocated memory (and it was right). And you'd already leaked the 24 bytes you allocated.
Corrected:
mem_ptr = (char*)malloc(24);
if (mem_ptr == NULL)
exit(EXIT_FAILURE);
strcpy(mem_ptr, "TEST");
printf("%s\n", mem_ptr);
free(mem_ptr);
Upvotes: 2