-
题目1
void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
程序崩溃,原因如下:
1、形参p是实参str的一份临时拷贝,对p进行的操作不影响str的值,str仍为NULL,在进行strcpy的过程中,对NULL进行解引用操作,程序崩溃
2、形参p记录了开辟的内存空间起始地址, GetMemory函数调用结束后p销毁,因此申请的内存空间的起始地址不知道了,这个过程造成了内存泄漏。
修改后的程序为:
void GetMemory(char** p)
{
*p = (char*)malloc(100);
}
void test(void)
{
char* str = NULL;
GetMemory(&str);
strcpy(str, "hello world");
printf(str);
free(str);
str = NULL;
}
结果为
-
题目2
char *GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char*str = NULL;
str = GetMemory();
printf(str);
}
程序结果为:
、
原因为GetMemory函数运行过程中产生的临时数组,数组的首元素地址传回,指针str进行接收,但是GetMemory函数调用完,临时数组被销毁,这块内存新内容不可知,str访问这块内存产生如上的结果,str成为野指针。
-
题目三
void GetMemory( char **p, int num )
{
*p = (char *) malloc( num );
}
void Test( void )
{
char *str = NULL;
GetMemory( &str, 100 );
strcpy( str, "hello" );
printf( str );
}
程序结果为
这个程序存在的错误为内存忘记释放
修改后为:
void GetMemory(char** p, int num)
{
*p = (char*)malloc(num);
}
void Test(void)
{
char* str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
free(str);//修改部分
str = NULL;
}
-
题目四
void Test(void)
{
char *str = (char *) malloc(100);
strcpy(str, "hello");
free(str);
if(str != NULL)
{
strcpy(str, "world");
printf(str);
}
}
运行结果为:
这个程序错误的原因是str成为野指针,没有置空。内存释放后,str对这块内存就没有使用权限了,但str仍旧记得这块空间的地址,所以对这块空间进行了非法访问和修改,将"hello"非法修改为"world"。这个程序修改方法为free后加str=NULL;