林锐的《高质量C/C++程序设计指南》有这样一个例子:
void GetMemory(char *p, int num)
{
p = (char*)malloc(sizeof(char)*num);
}
int main()
{
char *str = NULL;
GetMemory(str, 100);
strcpy(str, "hello");
}
书中也说这样用是完全错误的,但是错误的原因书中解释的并不是很容易让人理解
为了便于大家理解我们可以用gcc这个工具来查看汇编代码
以下是GetMemory函数:
.file "neicun.c"
.text
.align 2
.globl GetMemory
.type GetMemory,@function
GetMemory:
pushl %ebp
movl %esp, %ebp
subl $8, %esp
subl $12, %esp
pushl 12(%ebp)