简体   繁体   中英

Freeing memory that was allocated with malloc / Valgrind error

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM