7-4-1Test数的语句GetMemory(str, 200)并没有使str获得期望的内存,str依旧是NULL,为什么?
void GetMemory(char *p, int num)//zbf:感觉非常隐蔽,设计错误
{
p = (char *)malloc(sizeof(char) * num);
}
void Test(void)
{
char *str = NULL;
GetMemory(str, 100); // str 仍然为 NULL
strcpy(str, "hello"); // 运行错误
}
7-4-1
毛病出在函数GetMemory中。编译器总是要为函数的每个参数制作临时副本,指针参数p的副本是 _p,编译器使 _p = p。如果函数体内的程序修改了_p的内容,就导致参数p的内容作相应的修改。这就是指针可以用作输出参数的原因。在本例中,_p申请了新的内存,只是把_p所指的内存地址改变了,但是p丝毫未变。所以函数GetMemory并不能输出任何东西。事实上,每执行一次GetMemory就会泄露一块内存,因为没有用free释放内存。(注意其原理解释)
7-4-2
void GetMemory2(char **p, int num)
{
*p = (char *)malloc(sizeof(char) * num);
}void Test2(void)
{
char *str = NULL;
GetMemory2(&str, 100); // 注意参数是 &str,而不是str
strcpy(str, "hello");
cout<< str << endl;
free(str);
}
7-4-2
由于7-4-3
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);
}
7-4-3
returnreturn7-4-4
char *GetString(void)
{
char p[] = "hello world";//用数组
return p; // 编译器将提出警告
}
void Test4(void)
{
char *str = NULL;
str = GetString(); // str 的内容是垃圾
cout<< str << endl;
}
7-4-4 return
用调试器逐步跟踪Test4,发现执行str = GetString语句后str不再是NULL指针,但是str的内容不是“hello world”而是垃圾。
如果把7-4-4改写成7-4-5,会怎么样?
char *GetString2(void)
{
char *p = "hello world";//用指针
return p;
}
void Test5(void)
{
char *str = NULL;
str = GetString2();
cout<< str << endl;
}
7-4-5 return
函数Test5运行虽然不会出错,但是函数GetString2的设计概念却是错误的。因为GetString2内的“hello world”是常量字符串,位于静态存储区,它在程序生命期内恒定不变。无论什么时候调用GetString2,它返回的始终是同一个“只读”的内存块。 程序运行如下: vc->File->new->c++source file #include "iostream.h"#include "stdio.h"#include "string.h"#include "malloc.h" void GetMemory(char *p,int num);void Test(void);void GetMemory2(char **p,int num);void Test2(void);char *GetMemory3(int num);void Test3(void);char *GetString(void);void Test4(void);char *GetString2(void);void Test5(void); void main(){// Test(); Test2(); Test3(); Test4(); Test5();} void GetMemory(char *p,int num)//设计错误,却非常隐蔽{ p=(char*)malloc(sizeof(char)*num);}void Test(void){ char *str=NULL; GetMemory(str,100); strcpy(str,"hello"); cout<<str<<endl;}void GetMemory2(char **p,int num){ *p=(char*)malloc(sizeof(char)*num);}void Test2(void){ char *str=NULL; GetMemory2(&str,100);//注意参数传递 strcpy(str,"hello"); cout<<str<<endl; free(str);//保持与malloc的配对}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);//保持与malloc的配对}char *GetString(void){ char p[]="hello"; return p;//warning:return address of local variable or temporary(数组属于局部变量)}void Test4(void){ char *str=NULL; str=GetString(); cout<<"以下内容为垃圾: "; cout<<str<<endl;}char *GetString2(void){ char *p="hello"; return p;}void Test5(void){ char *str=NULL; str=GetString2(); cout<<str<<endl;}运行结果: hello hello 以下内容为垃圾:(随意的内容) hello