(1)如果函数的参数是一个指针,不要指望用该指针去申请动态内存。
#include <stdlib.h>
#include <string.h>
void GetMemory(char *p,int num)
{
p=(char *)malloc(sizeof(char)*num);//内存泄露
}
void Test(void)
{
char *str=NULL;
GetMemory(str,100);//str仍然为NULL
strcpy(str,"hello");
}
void main()
{
Test();
}
(2)指向指针的指针
#include <stdlib.h>
#include <string.h>
#include <iostream.h>
void GetMemory2(char **p,int num)
{
*p=(char *)malloc(sizeof(char)*num); //内存泄露
}
void Test(void)
{
char *str=NULL;
GetMemory2(&str,100);
strcpy(str,"hello");
cout<<str<<endl;
}
void main()
{
Test();
}
(3)函数返回值来传递动态内存
#include <stdlib.h>
#include <string.h>
#include <iostream.h>
char *GetMemory3(int num)
{
char *p=(char *)malloc(sizeof(char)*num); //内存泄露
return p;
}
void Test(void)
{
char *str=NULL;
str=GetMemory3(100);
strcpy(str,"hello");
cout<<str<<endl;
}
void main()
{
Test();
}
不要用return语句返回指向"栈内存"的指针,因为该内存在函数结束时自动消亡
#include <stdlib.h>
#include <string.h>
#include <iostream.h>
char *GetString(void)
{
char p[]="hello world";//在栈上被创建
return p;
}
void Test(void)
{
char *str=NULL;
str=GetString();//str的内容是垃圾
cout<<str<<endl;
}
void main()
{
Test();
}
设计概念错误
#include <stdlib.h>
#include <string.h>
#include <iostream.h>
char *GetString2(void)
{
char *p="hello world";//指针p指向常量字符串"hello world"
return p;
}
void Test(void)
{
char *str=NULL;
str=GetString2();
cout<<str<<endl;
}
void main()
{
Test();
}