free struct,內部指標並不free

來源:互聯網
上載者:User

C的struct的記憶體管理需要小心,尤其是struct內部還有指標的情況,free掉一個struct結構的指標,如果其struct內部有指標,該指標內容不釋放,這個在調用別人寫好的struct介面時,會相當麻煩,這就要求對方除了提供struct介面外,還提供額外的記憶體管理支援,否則很容易出現問題,在這點上,C++的建構函式、解構函式明顯表現要好的多,下面是一個free struct的C的例子:

#include
#include

struct test
{
 char* p_ch;
 int ix;
};

int main(int argc, char *argv[])
{
 struct test *p_test;
 p_test = malloc(sizeof(struct test));
 p_test->p_ch = malloc(20);
 char *p_ch = "Hello!";
 strcpy(p_test->p_ch, p_ch);
 p_ch = p_test->p_ch;
 printf("p_test->p_ch:/t%s/n", p_test->p_ch);
 free(p_test->p_ch); //如果注釋掉這行,p_ch值仍為“Hello!” 
  free(p_test);
 printf("after free(p_test), p_ch:/t%s/n", p_ch);
 

 system("PAUSE");?
 return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.