动态内存开辟空间的使用-经典面试题
//常见错误,
//1.对NULL指针的解引用操作
//int* p = malloc(40);
//*p = 10;//mallco开辟空间失败,-对NULL指针解引用,需要对p进行判断
//2.对动态开辟内存空间的越界访问
//3.对非动态开辟内存使用free释放
//4.使用free释放动态内存的一部分 做到谁开辟谁释放 加上p==NULL 将p指针指向空指针
int* p = (int*)malloc(40);
if (p==NULL)
{
return 0;
}
free(p);
p==NULL
free(p);
return 0;
}
//5.动态内存靠开辟忘记释放(内存泄漏
面试题:
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;
}
解析:
1.运行代码程序会出现崩溃
2.没有free出现内存泄漏的问题
3.str以值传递方式给p 因为str是指针要用二级指针接受
4.p是GetMemory函数的形参,只能在函数内部有效
5.GetMeory函数结束返回的时候,动态开辟内存尚未释放并且无法找到,hello world 无法向str的NULL里面传递,从而造成内存泄漏
#include <stdio.h>
#include <malloc.h>
#pragma warning(disable : 4996)
#include <string.h>
解决方法:传地址,用二级指针接收
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;
解决方法2:
char* GetMemory(char* p)
{
p = (char*)malloc(100);
return p;
}
void Test(void)
{
char* str = NULL;
str =GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
int main()
{
Test();
return 0;
}
浙公网安备 33010602011771号