C语言动态内存分配

时间:2023-03-09 19:42:40
C语言动态内存分配

考虑下面三段代码:

片段1

void GetMemory(char *p)
{
p = (char *)malloc();
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
free(str);
}

片段2

char *GetMemory(void)
{
char p[ ] = "hello world";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}

片段3

void GetMemory(char **p, int num)
{
*p = (char *) malloc(num);
} void Test(void)
{
char *str = NULL;
GetMemory(&str, );
strcpy(str, "hello world");
printf(str);
}

在执行代码:

int main()
{ Test(); return ;
}

上面三个片段中,1和2根本无法得到正确的结果。片段1甚至会引发程序崩溃!!!

阅读了林锐博士《高质量C/C++编程指南》,在内存管理方面发现确实有很多说道。。。

片段一中,Test 函数的语句 GetMemory(str, 200) 并没有使 str 获得期望的内存, str 依旧是 NULL。

毛病出在函数 GetMemory 中。编译器总是要为函数的每个参数制作临时副本,指针参数 p 的副本是_p ,编译器使_p = p 。如果函数体内的程序修改了_p 的内容,就导致参数 p 的内容作相应的修改。如果非得要用指针参数去申请内存, 那么应该改用 “指向指针的指针!!!!


片段2的错误显而易见,不能return 指向栈内容的指针!