ptr = malloc(0*sizeof(char));

最近,看了有關malloc(0)的返回值以及其他一些問題的討論,我把自己的感受和看法記錄如下:

問題:char* ptr = malloc(0*sizeof(char));

if(NULL == ptr)

      printf("got a NULL pointer");

else

     printf("got a Valid pointer");

請問:上面的程序輸出爲什麼?在C99的標準裏面解釋到,如果給malloc傳遞0參數,其返回值是依賴於編譯器的實現,但是不管返回何值,該指針指向的對象是不可以訪問的。在VC6編譯環境下,輸出“got a Valid pointer”

但是我試圖給該指針賦值,如:*ptr = ''a'' ;編譯器並沒有給出任何錯誤和警告信息,接着,我再輸出該值,printf("*ptr=%d/n",*ptr) ;也可以正常輸出。

但是當我用free(ptr) ;釋放內存的時候,出現錯誤,爲什麼呢?下面是我看了網友經過討論以後我比較認同的看法:

當malloc分配內存時它除了分配我們指定SIZE的內存塊,還會分配額外的內存來存儲我們的內存塊信息,用於維護該內存塊。因此,malloc(0)返回一個合法的指針並指向存儲內存塊信息的額外內存,我們當然可以在該內存上進行讀寫操作,但是這樣做了會破壞該內存塊的維護信息,因此當我們調用free(ptr)時就會出現錯誤。完整程序如下:

#include 
#include

int main()
{
 char *ptr ;
 ptr = malloc(0*sizeof(char)) ;
 
 if (NULL == ptr)
  printf("got a NULL pointer/n");
 else 
 {
  printf("got a Valid pointer/n");

  *ptr = ''a'
  printf("the value at %X is:%c/n",ptr,*ptr);

  free(ptr) ;//if we did not add this statement ,the program can run normnlly,or we will get 

// a runtime error.
 }
 return 0 ;
}

既然malloc另外分配內存來維護該內存塊,也就是說分配來用於維護該內存塊的內存的大小也是有限的,那麼到底是多少呢?這和可能也依賴於實現,在VC6下,是56BYTE,下面是測試程序:

#include 
#include 
#include

int main()
{
 char *ptr ;
 ptr = malloc(0*sizeof(char)) ;
 
 if (NULL == ptr)
  printf("got a NULL pointer/n");
 else 
 {
  printf("got a Valid pointer/n");
  // 有56個a,另外有一個字節用於保存''/0'
  strcpy(ptr,"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); 
  //printf("the value at %X is:%c/n",ptr,*ptr);
  printf("the string at %x is :%s/n",ptr, ptr);
 // free(ptr);
 }
 return 0 ;
}

此時我們沒有把free(ptr)編譯進來,同樣會發生異常,程序輸出很多個56個a,我暫時還不明白爲什麼?????如果把free(ptr);編譯進來,就會發生運行錯誤!

通過上面的討論和程序的驗證,確實證明了網友和我的想法是正確的,也就是malloc(0)還會額外分配一部分空間(在VC6下是56字節)用於維護內存塊。

兄弟們可以運行下上面的程序,願意的話幫我把爲什麼輸出很多個56個a出來這個問題解決掉!^_^我感激不盡。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章