C語言:題目--函數調用,記憶體,malloc找錯

來源:互聯網
上載者:User

標籤:

  

malloc

 

int* p = (int *) malloc (sizeof(int)*128);

//分配128個(可根據實際需要替換該數值)整型儲存單元,並將這128個連續的整型儲存單元的首地址儲存到指標變數p中.

 

在Linux中可以有這樣:malloc(0),這是因為Linux中malloc有一個下限值16Bytes,注意malloc(-1)是禁止的;但是在某些系統中是不允許malloc(0)的。

 

if (NULL == (p = (type *)malloc(sizeof (type)))) /*請使用if來判斷,這是有必要的*/

函數:函數傳參:值傳遞,單向傳遞,拷貝傳遞。

void GetMemory(char *p)

{

p = (char *)malloc(100);

}

void Test(void)

{

char *str = NULL;

GetMemory(str);

//值傳遞,單向傳遞,拷貝傳遞。

strcpy(str, "hello world");

printf(str);

}

str不能獲得p所指向的記憶體空間,形參值的改變不會影響實參值;並且malloc開闢的堆空間最後沒有釋放。

 

char *GetMemory(void)

{   

char p[] = "hello world";

return p;

//p:數組,棧空間;

//運行char p[] = "hello world"後,會開闢1塊記憶體。完畢後空間和資料都釋放。

}

void Test(void)

{

char *str = NULL;

str = GetMemory();

//空間被釋放掉了

printf(str);

}

 str不能獲得p所指向的記憶體空間,錯在子函數返回了一個指向棧空間的指標,該棧空間在函數調用結束之後就被系統回收了,p所指向的棧數組空間內的”hello world”可能已經被系統銷毀了

Void GetMemory(char **p, int num)

{

*p = (char *)malloc(num);

}

void test(void)

{

char *str = NULL;

GetMemory(&str, 100);

strcpy(str, "hello");   

printf(str);   

}

//可以列印出”hello”, 只是malloc開闢的堆空間最後沒有釋放。

 

void test(void)

{

char *str = (char *) malloc(100);

strcpy(str, “hello”);

free(str);       

if(str != NULL)

{

strcpy(str, “world”);

//不能操作已經被釋放的堆空間

printf(str);

}

}

//錯在堆空間已經釋放掉了卻仍在使用指向堆空間的指標。

void fun(char* str1, char* str2)

{

*str1 = *str2;

}

main()

{

char *str1="ABC\n";

char *str2="BCD\n";

fun(str1, str2);//都是唯讀,段錯誤。

printf(str1);

}

錯在通過指標修改字元常量區的內容

void f1(char *p)

{

p = (char *)malloc(100);

}

int test()

{

char *str = NULL;

f1(&str);//傳參類型不符

strcpy(str, "hello world");

printf(str);

}

//傳參類型不符並且malloc開闢的堆空間最後沒有釋放

 

 

 

 

 

C語言:題目--函數調用,記憶體,malloc找錯

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.