关于内存的思考题(摘自林锐高质量c++编程)
下面两个内存使用的例子中,存在一定相似:使用malloc分配内存。运行结果截然不同,本人愚钝,不能理解通透,请各位大侠给出对原理的思考。
1.运行结果:程序崩溃,原因是GetMemory不能传递动态内存。
void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
2.运行正常,内存泄漏
void GetMemory2(char **p, int num)
{
*p = (char *)malloc(num);
}
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
}