举例:
voidGetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
请问运行Test 函数会有什么样的结果?
答:程序崩溃(段错误)。因为GetMemory 并不能传递动态内存,Test 函数中的str 一直都是 NULL。strcpy(str, "helloworld");将使程序崩溃。
我们知道,通过函数传递动态内存的方式有两种:返回内存的地址或者使用二级指针。用返回值的方式很容易理解,可为什么不能使用一级指针呢?
#include <stdio.h>
#include <stdlib.h>
void func(int *p)
{
printf("in func:\n");
printf("before malloc:\n");
printf("&p = %p, p = %p\n", &p, p);
p = (int*)malloc(1024);
printf("after malloc:\n");
printf("&p = %p, p = %p\n", &p, p);
}
int main()
{
int *p = (int *)malloc(3);
printf("in main:\n");
printf("&p = %p, p = %p\n", &p, p);
func(p);
printf("in main:\n");
printf("&p = %p, p = %p", &p, p);
free(p);
return 0;
}
#include <stdlib.h>
void func(int *p)
{
printf("in func:\n");
printf("before malloc:\n");
printf("&p = %p, p = %p\n", &p, p);
p = (int*)malloc(1024);
printf("after malloc:\n");
printf("&p = %p, p = %p\n", &p, p);
}
int main()
{
int *p = (int *)malloc(3);
printf("in main:\n");
printf("&p = %p, p = %p\n", &p, p);
func(p);
printf("in main:\n");
printf("&p = %p, p = %p", &p, p);
free(p);
return 0;
}