我只是在学习C并且不明白为什么这一小段代码会导致内存泄漏:
mem_ptr=(char*)malloc(24);
if (mem_ptr == NULL){
exit(EXIT_FAILURE);
}
mem_ptr="TEST";
printf("%s\n",mem_ptr);
free(mem_ptr);
当我跑步时,Valgrind告诉我:
==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)
答案 0 :(得分:2)
您错过了strcpy()
:
mem_ptr=(char*)malloc(24);
mem_ptr="TEST";
这丢弃了指向已分配空间的唯一指针。当你试图释放"TEST"
然后valgrind
抱怨它没有分配内存(并且它是正确的)。你已经泄露了你分配的24个字节。
修正:
mem_ptr = (char*)malloc(24);
if (mem_ptr == NULL)
exit(EXIT_FAILURE);
strcpy(mem_ptr, "TEST");
printf("%s\n", mem_ptr);
free(mem_ptr);