例子一:不用goto,想想需要申请的指针是10个的话,程序怎么写?
void Func(void)
{
char* p1=null;
char* p2=null;
char* p3=null;
p1=(char*)malloc(10);
if(!p1) return;
p2=(char*)malloc(10);
if(!p2)
{
free(p1);
p1=null;
return;
}
p3=(char*)malloc(10);
if(!p3)
{
free(p1);
p1=null;
free(p2);
p2=null;
return;
}
//...
if(p1)
{
free(p1);
p1=null;
}
if(p2)
{
free(p2);
p2=null;
}
if(p3)
{
free(p3);
p3=null;
}
}
例子二:用goto
void Func(void)
{
char* p1=null;
char* p2=null;
char* p3=null;
p1=(char*)malloc(10);
if(!p1) goto Func_End_Process;
p2=(char*)malloc(10);
if(!p2) goto Func_End_Process;
p3=(char*)malloc(10);
if(!p3) goto Func_End_Process;
//...
Func_End_Process:
if(p1)
{
free(p1);
p1=null;
}
if(p2)
{
free(p2);
p2=null;
}
if(p3)
{
free(p3);
p3=null;
}
}