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 p[] = "hello world";
return p;
p[]数组为函数内的局部自动变量,在函数返回后,内存已经被释放。这是许多程序员常犯的错误,其根源在于不理解变量的生存期。
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);
strcpy(str, "hello");
printf(str);
}
请问运行Test函数会有什么样的结果?
答:
(1)能够输出hello
(2)Test函数中也未对malloc的内存进行释放。
(3)GetMemory避免了试题1的问题,传入GetMemory的参数为字符串指针的指针,但是在GetMemory中执行申请内存及赋值语句
*p = (char *) malloc( num );
后未判断内存是否申请成功,应加上:
if ( *p == NULL )
{
...//进行申请内存失败处理
}
&str是指针的地址,将指针的地址传给形参p,则p也指向str,
所以*p = (char *)malloc(sizeof(char) * num);也就是给p所指向的str分配了内存,所以正确。
<4>
void Test(void)
{
char *str = (char *) malloc(100);
strcpy(str, “hello”);
free(str);
if(str != NULL)
{
strcpy(str, “world”);
printf(str); //str为野指针,打印的结果不得而知
}
}
请问运行Test函数会有什么样的结果?
答:执行
char *str = (char *) malloc(100);
后未进行内存是否申请成功的判断;另外,在free(str)后未置str为空,导致可能变成一个“野”指针,应加上:
str = NULL;
<5>
void Test6()
{
char *str=(char *)malloc(100);
strcpy(str, "hello");
str+=6;
free(str);
if(str!=NULL)
{
strcpy(str, "world");
printf(str);
}
}
//VC断言失败,运行错误
<6>
char *GetString(void)
{
char p[] = "hello world";
return p; // 编译器将提出警告
}
void Test4(void)
{
char *str = NULL;
str = GetString(); // str 的内容是垃圾
cout<< str << endl;
}
不要用return语句返回指向“栈内存”的指针,因为该内存在函数结束时自动消亡;
<7>
char *GetString2(void)
{
char *p = "hello world";
return p;
}
void Test5(void)
{
char *str = NULL;
str = GetString2();
cout<< str << endl;
}
函数Test5运行虽然不会出错,但是函数GetString2的设计概念却是错误的。因为GetString2内的“hello world”是常量字符串,位于静态存储区,它在程序生命期内恒定不变。无论什么时候调用GetString2,它返回的始终是同一个“只读”的内存块。
<8>
void test(void)
{
char *p = (char *) malloc(100);
strcpy(p, “hello”);
free(p); // p 所指的内存被释放,但是p所指的地址仍然不变
…
if(p != NULL) // 没有起到防错作用
{
strcpy(p, “world”); // 出错
}
}
<9>
char *GetMemory3(int num)
{
char *p = (char *)malloc(sizeof(char) * num);
return p;
}
void Test3(void)
{
char *str = NULL;
str = GetMemory3(100);
strcpy(str, "hello");
cout<< str << endl;
free(str);
}
--------------------正确