管理动态内存的五大常见错误
对NULL指针的解引用
//错误
void test()
{
int* p = (int*)malloc(INT_MAX / 4);
*p = 20;//未对内存开辟进行判断,可能为NULL
free(p);
}
//常见解决方案
void text()
{
int* p = (int*)malloc(INT_MAX / 4);
if(p == NULL)
{
printf("%s",strerror(errno)); //打印错误信息
return;//终止
}
free(p);
}
对空间的越界访问
void test()
{
int *p = (int*)malloc(10);
if( p == NULL)
{
printf("%s",strerror(errno));
return;
}
int i = 0;
for(i = 0; i <= 10 ; i++)
{
*(p+i) = i;// i = 10 时造成越界
}
free(p);
}
free的错误释放
void test()
{
int a = 10;
int *p = &a;
free(p) // 不是内存空间;
int *pp = (int*)malloc(10);
if( pp == NULL)
{
printf("%s",strerror(errno));
return;
}
free(pp);
free(pp); // 重复释放
}
free释放不充分
void test()
{
int *p = (int*)malloc(10);
if( p == NULL)
{
printf("%s",strerror(errno));
return;
}
p++;
free(p); //未指向内存起始位置
}
内存泄漏(未释放)
int* test()
{
int *p = (int*)malloc(100);
if( p == NULL)
{
printf("%s",strerror(errno));
return p;
}//没有释放
return p;
}
int main()
{
int* ret = text();
return 0;
}