[英]How to free NULL pointer after using malloc
例如,我有下面的代碼來計算指針的大小(如本例中的數組):
#include <stdio.h>
#include <stdlib.h>
int **ptr;
void init() {
ptr = malloc(sizeof(int *)*5);
if(!ptr){
printf("cannot malloc, \n");
return;
}
for(int i =0; i < 5; i++) {
ptr[i] = malloc(sizeof(int));
if(!ptr[i]){
printf("cannot malloc, ptr[%d]\n", i);
return;
}
}
ptr[4] = NULL;
}
int main(void) {
init();
int count = 0;
while(ptr[count] != NULL) {
count++;
}
printf("size of ptr = %d\n", count);
}
在init()
function 中的數組的和處添加 NULL 指針,然后使用while
循環通過增加count
來計算大小,直到滿足 NULL 指針。 這是個壞主意嗎?
據我所知,對於free(pointer)
function,如果pointer
是 NULL,則沒有任何反應。 那么,如何釋放ptr[4]
?
我嘗試釋放這個指針:
for(int i =0; i < 5; i++) {
free(ptr[i]);
}
free(ptr);
然后通過 Valgrind 驗證
==2957== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1
==2957== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2957== by 0x108775: init (test2.c:12)
==2957== by 0x1087E1: main (test2.c:22)
==2957==
==2957== LEAK SUMMARY:
==2957== definitely lost: 4 bytes in 1 blocks
==2957== indirectly lost: 0 bytes in 0 blocks
==2957== possibly lost: 0 bytes in 0 blocks
==2957== still reachable: 0 bytes in 0 blocks
==2957== suppressed: 0 bytes in 0 blocks
我可以嘗試的一件事是使用realloc
(我知道realloc(PTR, 0)
不等同於free(PTR)
):
ptr[4] = realloc(ptr[4], 0);
但是當我通過 Valgrind 測試時仍然存在內存泄漏。
您 malloc 一些 memory,將該值存儲在ptr[4]
中,然后用NULL
覆蓋ptr[4]
。 這是您的 memory 泄漏發生的地方。 之后您所做的任何事情都無法恢復丟失的 memory。
您需要在 4(而不是 5)處停止循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.