设为首页 加入收藏

TOP

C语言 有关内存的思考题
2019-03-26 22:08:20 】 浏览:89
Tags:语言 有关 内存 考题

非原创。

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

 

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

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C语言的一道数组题Plus 下一篇C语言之输入月收入,输出该月应纳..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目