2011-06-12 91 views
0

我定義了以下函數,其中List是一個結構。爲什麼我的calloc無法將所有東西都歸零?

List * LIST_Create() 
{ 
    List * l = calloc(0, sizeof(List)); 
    unsigned char * pc = (unsigned char *)l; 
    for(i = 0; i < sizeof(List); i++) 
    { 
    LOG("LIST","0x%1x ", (unsigned char)*pc); 
    pc++; 
    } 
} 

當我打印出來的字節我得到這個:

LIST: 0xffffffbf 
LIST: 0x1 
LIST: 0x13 
LIST: 0x0 
LIST: 0x1 
LIST: 0x1 
LIST: 0x0 
LIST: 0x0 
LIST: 0x0 
LIST: 0x0 
LIST: 0x0 
LIST: 0x5 

這是怎麼回事?我知道這不是打印問題,因爲代碼也讀取非零值。我能夠可靠地將List結構清零的唯一方法似乎是單獨初始化所有成員。我不介意,但不應該calloc()工作?

+3

「malloc(0)'應該返回一個唯一的非零指針」羣體的另一個原因是破解...如果'calloc'已經返回了'NULL'程序會立即崩潰,並且錯誤會很明顯... – 2011-06-12 17:39:26

+0

@R。有趣。 – BeeBand 2011-06-12 18:10:57

回答

6

您分配的空間足夠0List S:

List * l = calloc(0, sizeof(List)); 

因此你分配的內存是0字節長。

1

您正在請求分配零字節。 calloc分配的大小爲nmemb*size,您有nmemb == 0

3

calloc(0, sizeof(List))分配一個0長度的緩衝區;您在創建「虛擬」指針後打印隨機數據,以便稍後您可以realloc()calloc的參數是項目的數量和單個項目的大小;這使得更容易分配例如5 (struct foo)的矢量。

1

你打電話給calloc 0元素(沒有元素)。你至少必須通過1:

List* l = calloc(1,sizeof(List)); 
2

手冊上說:

calloc() allocates memory for an array of nmemb elements of size bytes 
    each and returns a pointer to the allocated memory. The memory is set 
    to zero. If nmemb or size is 0, then calloc() returns either NULL, or 
    a unique pointer value that can later be successfully passed to free(). 

你的函數調用List * l = calloc(0, sizeof(List));

因此,你必須在0長度內存塊的地址或NULLl。 (可能你已經與memset混淆了?)

+0

是的。事實上,我把它和memset()混合起來了。 – BeeBand 2011-06-12 18:11:41

相關問題