有关内存的程序问题
(1)
void GetMemory(char*p)
{
p = (char*)malloc(57);
}
void main()
{
char*str = NULL;
GetMemory(str);
strcpy(str, "bit C++");
printf(str);
}
程序崩溃,由于GetMemory采用值传递,p的值没有使void中的str变化
(2)
char*GetMemory(void)
{
char p[]="bit C++";
return p;//返回p的首地址
}
void main()
{
char*str = NULL;
str = GetMemory;
printf(str);
}
程序乱码
(3)
char GetMemory(char**p)
{
*p=(char*)malloc(57);
}
void main()
{
char*str = NULL;
GetMemory(&str);
strcpy(str, "bit C++");
printf(str);
}
可以输出bit C++,但是内存泄露,应该free(str);
(4)
void main()
{
char *str = (char*)malloc(57);
strcpy(str, "bit");
free(str);
if (str != NULL)
{
strcpy(str, "C++");
printf(str);
}
}
free(str)之后str变成野指针,并没有置空,if语句不起作用
转载于:https://blog.51cto.com/zhangxinbei/1748457