首页 > 编程语言 > 详细

C语言 有关内存的思考题

时间:2015-04-17 15:41:11      阅读:150      评论:0      收藏:0      [点我收藏+]

1.

void GetMemory(char *p)
{
     p = (char *)malloc(100);
}
void Test(void)
{
     char *str=NULL;
     GetMemory(str);
     strcpy(str,"Hello World");
     printf(str);
}

请问运行Test函数会有什么样的结果?
程序编译可以通过,运行中出现内存错误。
因为GetMemory不能传递动态内存,Test函数中的str一直都是NULL。strcpy(str,”Hello World”);将由于str中没有开辟足够的内存空间而使内存崩溃。

2.

char *GetMemory(void)
{
     char p[] = "Hello World";
     return p;
}
void Test(void)
{
     char *str=NULL;
     str = GetMemory();
     printf(str);
}

请问运行Test函数会有什么样的结果?
程序编译通过,可能显示为乱码。
因为GetMemory返回的是指向“栈内存”的指针,该指针的地址不是NULL,但其原先的内容已经被清除,新内容不确定,可能显示为乱码。

3.

void GetMemory2(char **p,int num)
{
     *p = (char *)malloc(num);
}
void Test(void)
{
     char *str=NULL;
     GetMemory2(&str,100);
     strcpy(str,"Hello World");
     printf(str);
}

请问运行Test函数会有什么样的结果?
程序编译通过,能够正确输出Hello World,但是对于malloc没有free,造成内存泄漏。

4.

void Test(void)
{
     char *str=(char *)malloc(100);
     strcpy(str,"Hello");
     free(str);
     if(NULL != str)
     {
          strcpy(str,"World");
          printf(str);
     }
}

请问运行Test函数会有什么样的结果?
程序编译通过,但是篡改动态内存区的内容,后果难以预料,非常危险。
因为free(str);之后,str成为野指针,if(NULL != str)语句对str不起作用,在str成为野指针之后,又继续为str指针赋值,可能会缠上难以预料的后果。

具体了解C语言中内存管理可查阅:
C/C++中内存管理相关知识

C语言 有关内存的思考题

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!