1.(非法访问内存问题)
char *GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}
结果打印随机值,Test函数调用GetMemory函数时,GetMemory函数在栈区上开辟一段空间,内容为hello world,函数GetMemory返回指针P指向的空间的地址,但离开GetMemory时该空间已被销毁,所以str指针指向的空间内容未知。因此不会打helloworld。在p[]前加static即可,将该空间放入静态区。
2.内存泄漏问题
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;
}
这里能打印出hello,但是打印过后动态开辟的内存未被释放,会出现内存泄漏的问题,在test函数后将str指向的空间释放,并且将str设为空指针。
3.释放后的空间再次被使用
void Test(void)
{
char *str = (char *) malloc(100);
strcpy(str, "hello");
free(str);
if(str != NULL)
{
strcpy(str, "world");
printf(str);
}
}
这里free函数释放str指向的空间后,并不会把str置为NULL,free之后,应将指针置为空。