[英]free 2D array allocated using calloc
我正在使用二維數組,並且需要分配它,如下所示:
char ** buf; //global var
void allocate()
{
buf = (char **) malloc (10 * sizeof (char*));
char * data = (char *) calloc (1, 1000);
int i;
for(i=0; i<10; i++)
buf[i] = &(data[i*100]);
}
int main()
{
allocate();
//something goes here
free(buf[0]);
free(buf);
return 0;
}
現在釋放 arrays,因為我無法訪問main()中的變量“數據”,我無法執行free(data) ,因此我執行free(buf[0]) ,假設我正在釋放 1000 個元素的整個數組. 這是正確的方法嗎? free(buf[0]) 是否釋放整個“數據”數組?
(將 buf 的每個元素 malloc 設置為 buf[i] = malloc (100) 會很方便,但我不能這樣做,因為我必須先調用一個大塊)。
提前致謝。
這段代碼是正確的。 buf[0]
的值是&(data[0])
,根據定義是data
。 這將釋放所有已分配的 memory。
請注意,如果您真的只想釋放一個緩沖區,您可以設置:
offset = 10*sizeof(char*);
buf = calloc(10*100+offset);
並在循環中執行:
buf[i] = buf + offset + i*100;
這有點不尋常,但它是正確的。 你做了兩次分配; 你做了兩個免費的。 然后釋放已分配的指針。 一切都應該是干凈的。
你在你的程序上運行了valgrind
嗎?
Valgrind 同意你的觀點。 這是正確的,因為 buf[0] 持有指向 calloc'd memory 塊的 HEAD 的指針。
valgrind ./temp
==15404== Memcheck, a memory error detector
==15404== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==15404== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==15404== Command: ./temp
==15404==
==15404==
==15404== HEAP SUMMARY:
==15404== in use at exit: 0 bytes in 0 blocks
==15404== total heap usage: 2 allocs, 2 frees, 1,040 bytes allocated
==15404==
==15404== All heap blocks were freed -- no leaks are possible
==15404==
==15404== For counts of detected and suppressed errors, rerun with: -v
==15404== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 12 from 7)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.