C語言 有關內存的思考題

非原創。函數

今天筆試時候遇到的問題,原文連接見底部。spa

 

1.net

 1 void GetMemory(char *p)  2 {  3     p = (char *)malloc(100);  4 }  5 void Test(void)  6 {  7     char *str=NULL;  8  GetMemory(str);  9     strcpy(str,"Hello World"); 10  printf(str); 11 }

程序編譯能夠經過,運行中出現內存錯誤。
由於GetMemory不能傳遞動態內存,Test函數中的str一直都是NULL。strcpy(str,」Hello World」);將因爲str中沒有開闢足夠的內存空間而使內存崩潰。指針

 

2code

 1 char *GetMemory(void)  2 {  3     char p[] = "Hello World";  4     return p;  5 } void Test(void)  6 {  7     char *str=NULL;  8     str = GetMemory();  9  printf(str); 10 }

程序編譯經過,可能顯示爲亂碼。
由於GetMemory返回的是指向「棧內存」的指針,該指針的地址不是NULL,但其原先的內容已經被清除,新內容不肯定,可能顯示爲亂碼。blog

3內存

 1 void GetMemory2(char **p,int num)  2 {  3     *p = (char *)malloc(num);  4 }  5 void Test(void)  6 {  7     char *str=NULL;  8     GetMemory2(&str,100);  9     strcpy(str,"Hello World"); 10  printf(str); 11 }

程序編譯經過,可以正確輸出Hello World,可是對於malloc沒有free,形成內存泄漏。編譯

4class

 1 void Test(void)  2 {  3     char *str=(char *)malloc(100);  4     strcpy(str,"Hello");  5     free(str);  6     if(NULL != str)  7  {  8         strcpy(str,"World");  9  printf(str); 10  } 11 }

程序編譯經過,可是篡改動態內存區的內容,後果難以預料,很是危險。
由於free(str);以後,str成爲野指針,if(NULL != str)語句對str不起做用,在str成爲野指針以後,又繼續爲str指針賦值,可能會產生難以預料的後果。亂碼

 

 

 

原文:https://blog.csdn.net/veno813/article/details/45097131

相關文章
相關標籤/搜索