看下面的例子:
#include<stdio.h>
#include<stdlib.h>
void free_int(int *p)
{
if( p != NULL)
{
free(p);
}
}
int main()
{
int ret = 0;
int *p = NULL;
int *q = NULL;
p = (int *)malloc(10000);
if(p == NULL)
{
ret = -1;
printf("func malloc error: %d(p == NULL)",ret);
return ret;
}
q = (int *)malloc(10000);
if(p == NULL)
{
ret = -1;
printf("func malloc error: %d(q == NULL)",ret);
return ret;
}
free_int(p);
p = NULL;
free_int(q);
q = NULL;
system("pause");
return ret;
}
上面这段程序,只是做说明使用未实现任何功能:这段程序在什么时候会发生内存泄露呢?当q分配内存失败时候.if(p ==NULL)成立时候。函数直接return了。从而导致p所指向的内存空间泄露。这里我们可以借助goto 语句;
#include<stdio.h>
#include<stdlib.h>
void free_int(int *p)
{
if( p != NULL)
{
free(p);
}
}
int main()
{
int ret = 0;
int *p=NULL;
int *q = NULL;
p = (int *)malloc(100);
if(p == NULL)
{
ret = -1;
printf("func malloc error: %d(p == NULL)",ret);
return ret;
}
q = (int *)malloc(100);
if(p == NULL)
{
ret = -1;
printf("func malloc error: %d(q == NULL)",ret);
goto End;// goto End 而不是return
}
End:
free_int(p);
p = NULL;
free_int(q);
q = NULL;
system("pause");
return ret;
}
当q分配内存失败时候.if(p ==NULL)成立时候。函数直接goto 到End 语句处了,就可以将内存空间释放到了,从而有效的避免内存泄露。