四、有关内存的思考题(20分)
void GetMemory(char *p)
{
p = (char *)malloc(100);
}void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
请问运行Test函数会有什么样的结果?
答:
char *GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}
请问运行Test函数会有什么样的结果?
答:
Void GetMemory2(char **p, int num)
{
*p = (char *)malloc(num);
}
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
}
请问运行Test函数会有什么样的结果?
答:void Test(void)
{
char *str = (char *) malloc(100);
strcpy(str, “hello”);
free(str);
if(str != NULL)
{
strcpy(str, “world”);
printf(str);
}
}
请问运行Test函数会有什么样的结果?
答:
void GetMemory(char *p)
{
p = (char *)malloc(100);
}void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
请问运行Test函数会有什么样的结果?
答:
char *GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}
请问运行Test函数会有什么样的结果?
答:
Void GetMemory2(char **p, int num)
{
*p = (char *)malloc(num);
}
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
}
请问运行Test函数会有什么样的结果?
答:void Test(void)
{
char *str = (char *) malloc(100);
strcpy(str, “hello”);
free(str);
if(str != NULL)
{
strcpy(str, “world”);
printf(str);
}
}
请问运行Test函数会有什么样的结果?
答:
2.输出一个不是想要的值。
3.hello
4.world
2、char p[]是局部动态数组,其储存空间是在栈中分配,在函数返回后其空间被释放,调用其它函数时则可能分配给其它函数中的动态变量使用,所以数据未知(与printf函数的内部实现有关)。
3、传递地址可以在函数中修改地址中的数据,函数返回后str是malloc分配的内存指针。
4、在堆中分配的内存被释放后,内存空间有可能立即释放,也有可能没有立即释放,所以结果未知。
2、char p[]是局部变量,储存空间是在栈中分配,在函数返回后其空间被释放。
3、引用传递可以在函数中修改该地址的副本,函数返回后str得到分配后的内存。
4、在堆中分配的内存释放后,该内存空间有可能立即释放,也有可能没有立即释放。此时
指针仍然指向此处,所以结果未知。应该在free后将指针置为空。
2、局部变量,返回后,函数释放,访问可能异常
3、正确修改指针指向的内容,输出hello
4、释放堆上数据,然后访问,结果不可预知的错误
2.可能输出乱码等,(结果不一定)与栈空间的再利用有关系,看printf如何处理的。
3.正常输出,输出结果为:hello
4.出现野指针,但是输入结果不可预测。
http://topic.csdn.net/u/20090220/12/9b07f419-f1a5-4bd4-8f67-60b8d2609d23.html?seed=1217100858
因为GetMemory并不能传递动态内存,Test函数中的str一直都是NULL。strcpy(str, "hello world");将使程序崩溃。2、可能是乱码。
因为GetMemory返回的是指向“栈内存”的指针,该指针的地址不是NULL,但其原现的内容已经被清除,新内容不可知。3、能够输出hello;内存泄漏。4、篡改动态内存区的内容,后果难以预料,非常危险。因为free(str);之后,str成为野指针,if(str != NULL)语句不起作用。