题目1:
void GetMemory(char *p)
{
*p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world"); 对NULL指针解引用操作符程序崩溃。
printf(str);
}
请问运行Test函数会有什么样的后果?
- GetMoemory函数采用值传递的方式,无法将malloc开辟空间的地址返回放在str中,调用后str依然是NULL指针。
- strcpy中使用了str,就是对NULL解引用操作,程序会崩溃。
- 内存泄漏。
应该让GetMoemory函数采用地址传递的方式,使用二级指针。并且应该在使用结束后,将malloc出来的空间释放掉。
题目2:
char *GetMemory(void)
{
char p[] = "hello world";
return p; 出了函数p为野指针
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}int main(){
test();