非原创。
今天笔试时候遇到的问题,原文链接见底部。
1
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中没有开辟足够的内存空间而使内存崩溃。
2
1 char *GetMemory(void)2 {3 char p[] = "Hello World";4 returnp;5 } void Test(void)6 {7 char *str=NULL;8 str =GetMemory();9 printf(str);10 }
程序编译通过,可能显示为乱码。
因为GetMemory返回的是指向“栈内存”的指针,该指针的地址不是NULL,但其原先的内容已经被清除,新内容不确定,可能显示为乱码。
3
1 void GetMemory2(char **p,intnum)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,造成内存泄漏。
4
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