[英]Freeing elements of a void pointer array
我正在調試其他人編寫的某些代碼,Valgrind檢測到了幾次內存泄漏。 我認為引起問題的部分代碼涉及void
指針:
int noElements = 100;
void** ptr = malloc( noElements * sizeof(void*));
for(int i = 0; i < noElements; i++)
{
ptr[i] = malloc(sizeof(void*));
}
//Operation filling the array and doing calculation
free(ptr); //This will not clear the underlying array causing the memory leak?
我創建了一個小型測試程序來檢查錯誤所在的位置(在調用free(ptr);
之前不釋放每個ptr[i]
),但是在嘗試釋放元素時出現錯誤。 我的測試程序如下所示:
int main()
{
int num = 10000000; //Large array so I can clearly see memory usage
void** ptr = (void**) malloc(sizeof(void*) * num);
for (int i = 0; i < num; i++)
{
ptr[i] = malloc(sizeof(void*));
ptr[i] = &i; //If I never point elements at anything, this code works
}
for (int i = 0; i < num; i++)
{
free(ptr[i]); //Crashes here if the elements have been pointed at a variable
}
free(ptr);
return 0;
}
如果實際上已分配了指針,為什么在每個數組元素上調用free會導致程序崩潰?
您的指針被分配了一個不是您想要的值。
for (int i = 0; i < num; i++)
{
ptr[i] = malloc(sizeof(void*));
ptr[i] = &i; //If I never point elements at anything, this code works
}
首先,您分配一個有效的內存地址,該地址由malloc()
返回。 該地址可以使用free()
釋放。 但是,然后您分配另一個地址。 您的局部變量i
的地址。 此內存位置未使用malloc()
分配,因此無法釋放。 通過分配此地址,您丟失了動態分配的地址,從而導致內存泄漏。
您的評論是錯誤的。 您已經分配了一個指向ptr[i]
指向某個有效地址的值。 您無需再次分配。 而且你不應該。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.