杜绝返回函数内局部变量的指针或者引用
//函数定义
char *GetStr(){
char str[] = "hello" ; // 局部变量,函数运行完释放
return str;
}
char *GetStr2()
{
char *str2 = "hello"; //“hello”保存在只读常量去,不在栈内分配
return str2; //返回str2的副本(str2被注销)
char *GetStr3()
{
char *str3= new char[6]; //在堆区分配,如果没用delete,则内存不释放,导致内存泄露(这里只是为了举例子)
str3[0] = 'h';
str3[1] = 'e';
str3[2] = '1';
str3[3] = '1';
str3[4] = 'o';
str3[5] = '\0';
//str3未释放,导致内存泄露(这里只是为了举例子);
return str3;
}
int main()
{
char *p = GetStr();
char *p2 = GetStr2();
char *p3 = GetStr3();
printf("%s\n", p);
printf("%s\n", p2);
printf("%s\n", p3);
}
运行结果如下图: