林锐高质量C++关于内存的思考题

2022-03-13  本文已影响0人  红枫叶HM

转载自:http://blog.sina.com.cn/s/blog_6c8304c101014hp9.html

void GetMemory(char *p)

{

p = (char *)malloc(100);

printf("%p\n", p); // 输出:00761770

}

void Test(void)

{

char *str = NULL;

GetMemory(str);

printf("%p\n", str); // 输出:00000000

strcpy(str, "hello world");

printf(str);

}

运行结果:程序崩溃。GetMemory()函数是无法传递动态分配的内存的,所以指针str一直为NULL。

char *GetMemory(void)

{

char p[] = "hello world";

printf("%p\n", p); // 输出:0022FF00

return p;

}

int main(void)

{

char *str =NULL;

str = GetMemory();

printf("%p\n", str); // 输出:0022FF00

printf(str);

}

运行结果:可能输出乱码。此例指针str能获得GetMemory()返回的指针p及其指向的内容;输出乱码是因为指针p是指向栈内存的指针,赋给str时其内存已经被释放,指向的内容也被清空,但指针p仍存在,其任意指向一块内存,此块内存的内容(str获得的内容)不可知。

以上两例可以如下修改:


void GetMemory(char **p)

{

*p = (char *)malloc(100);

}

void Test(void)

{

char *str = NULL;

GetMemory(&str);

strcpy(str, "hello world");

printf(str);

free(str);// 必须释放,否则会造成内存泄露

}

char *GetMemory(void)

{

char *p =(char *)malloc(100);

return p;

}

int main(void)

{

char *str =NULL;

str = GetMemory();

printf(str);

free(str);

}
int main(void)

{

char *str = (char *)malloc(100);

printf("%p\n", str); // 输出:00591770

strcpy(str, "hello");

free(str); // 错误

printf("%p\n", str); // 输出:00591770

if(str != NULL)

{

strcpy(str, "world");

printf(str);

}

}

运行结果:无法预测。指针str被free后,指针str不为NULL且指向一块不确定的内存,向一块不确定的内存拷贝内容,结果无法预测。

free()的作用:释放为指针动态分配的内存(指针指向的内容被清空,但是指针仍存在)。

上一篇下一篇

猜你喜欢

热点阅读