1.关于动态申请内存的问题 出现率极高
程序的局部变量存在于(栈)中
程序的全局变量存在于(静态存储区)中
程序动态申请的数据存在于(堆)中
程序的全局变量存在于(静态存储区)中
程序动态申请的数据存在于(堆)中
<1>
void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test1(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str); //str一直是空,程序崩溃
}
请问运行Tes1t函数会有什么样的结果?
答:试题传入GetMemory( char *p )函数的形参为字符串指针,在函数内部修改形参并不能真正的改变传入形参的值,执行完
char *str = NULL;
GetMemory( str );
后的str仍然为NULL;
毛病出在函数GetMemory 中。编译器总是要为函数的每个参数制作临时副本,指针参数p的副本是 _p,编译器使 _p = p。如果函数体内的程序修改了_p的内容,就导致参数p的内容作相应的修改。这就是指针可以用作输出参数的原因。在本例中,_p申请了新的内存,只是把 _p所指的内存地址改变了,但是p丝毫未变。所以函数GetMemory并不能输出任何东西。事实上,每执行一次GetMemory就会泄露一块内存,因为没有用free释放内存。
<2>
char *GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test2(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}
请问运行Test2函数会有什么样的结果?
答:可能是乱码。
char *GetMemory3(void)
{
return "hello world";
}
void Test3(void)
{
char *str = NULL;
str = GetMemory3();
printf(str);
}
Test3 中打印hello world,因为返回常量区,而且并没有被修改过。
<3>
void GetMemory2(char **p, int num)
{
*p = (char *)malloc(num);
}
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100);