標籤:
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找錯