您的位置:首页 > 其它

几个关于内存的问题

2016-07-26 00:42 477 查看
问题:请问下面几个程序运行起来的结果分别是什么?

1.

void GetMemory(char *p)
{
p = (char *)malloc(100);
}
int main()
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
system("pause");
return 0;

}
答:程序崩溃。
         因为GetMemory函数是无法传递动态开辟的空间的,所以主函数里的str一直都是NULL,这时程序再调用strcpy()函数,字符串str就没有空间拷贝“hello world”,从而程序崩溃。

2.

#include<stdio.h>
#include<string.h>
char *GetMemory()
{
char p[] = "hello world";
return p;
}
void main(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
system("pause");
}
答:输出乱码。

        因为在GetMemory函数里的字符串是局部变量,局部变量是存放在栈里面,所以return语句最终返回的是栈内存的指针,而这个指针在函数体结束后是要被销毁的,所以现在返回的内容是不可知的。

3.

void GetMemory(char **p, int num)
{
*p = (char *)malloc(num);
}
void main(void)
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
system("pause");
}
答:输出hello。

        这里可以输出hello,但是存在内存泄漏问题。

4.

void main()
{
char *str = (char *)malloc(100);
strcpy(str, "hello");
free(str);
if (str != NULL)
{
strcpy(str, "world");
printf(str);
}
system("pause");
}
答:输出world。

        在这里str被释放掉了,str!=NULL起不到不起作用,str变成了野指针!!!!!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  内存 基础知识