当前位置: 移动技术网 > IT编程>开发语言>C/C++ > C语言 有关内存的思考题

C语言 有关内存的思考题

2019年03月27日  | 移动技术网IT编程  | 我要评论

绝世媚妃,中星6b卫星最新参数,墨墨温情

非原创。

今天笔试时候遇到的问题,原文链接见底部。

 

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     return p; 
 5 } void test(void) 
 6 { 
 7     char *str=null; 
 8     str = getmemory(); 
 9     printf(str); 
10 }

程序编译通过,可能显示为乱码。
因为getmemory返回的是指向“栈内存”的指针,该指针的地址不是null,但其原先的内容已经被清除,新内容不确定,可能显示为乱码。

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,造成内存泄漏。

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

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网