问题1 请问运行Test函数会有什么样的结果?
void GetMemory(char* p)
{
p = (char*)malloc(100);
}
void Test(void)
{
char* str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
int main()
{
Test();
return 0;
}
函数GetMemory执行结束后,指针变量p被销毁,所以str还是NULL。所以最后肯定打印不出结果。
问题2 请问运行Test函数会有什么样的结果?
char* GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char* str = NULL;
str = GetMemory();
printf(str);
}
int main()
{
Test();
return 0;
}
函数GetMemory执行结束,变量被销毁。指针变量p不能把指向的地址传给str,故str指向地址变为随机值,故打印结果为随机值。
问题3 请问运行Test函数会有什么样的结果?
void GetMemory(char** p, int num)
{
*p = (char*)malloc(num);
}
void Test(void)
{
char* str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
}
int main()
{
Test();
return 0;
}
正确打印了hello。利用二级指针做函数形参,成功把str变成分配的大小为100字节连续空间的的起始地址。但是没有用free进行内存释放,造成内存泄漏。
问题4 请问运行Test函数会有什么样的结果?
void Test(void)
{
char* str = (char*)malloc(100);
strcpy(str, "hello");
free(str);
if (str != NULL)
{
strcpy(str, "world");
printf(str);
}
}
int main()
{
Test();
return 0;
}
打印出world。malloc申请的100字节空间的起始地址放在str里。free这100字节空间后,之前strcpy的hello自然消失。但是没有进行str赋值为NULL的操作,所以str依然为该空间的起始地址。所以正常进行strcpy(str, "world");,最后打印world。