Today, when I was maintaining a C Project, I found that some functions have many return statements, and each return has a piece of code for releasing the same resource. The code looks like this:
Int f (){
Char * p1 = (char *) malloc (1024 * sizeof (char ));
Int * p2 = (int *) malloc (10 * sizeof (int ));
...
If (...){
Free (p1 );
Free (p2 );
Return 1;
}
For (...){
If (...){
Free (p1 );
Free (p2 );
Return 2;
}
}
...
Free (p1 );
Free (p2 );
Return 0;
}
The above code resources release a part of the repeat too high, not refreshing enough to read. More importantly, if you forget to release resources before a return, memory leakage may occur. You can only rely on the author and maintainer of the program to be vigilant at any time. This type of problem can be solved through RAII in C ++, but the C language does not have an automatic structure analysis mechanism. Therefore, we need some skills to achieve similar results. See the following code:
Int void f (){
Int return_code = 0;
Char * p1 = (char *) malloc (1024 * sizeof (char ));
Int * p2 = (int *) malloc (10 * sizeof (int ));
...
If (...){
Return_code = 1;
Goto _ END_F;
}
For (...){
If (...){
Return_code = 2;
Goto _ END_F;
}
}
...
_ END_F:
Free (p1 );
Free (p2 );
Return return_code;
}
We put the resource release code at the end of the function and add the _ END_F tag to replace the original return with goto _ END_F. In this way, we eliminate the redundant code for releasing resources, and reduce the risk of forgetting to release resources to a certain extent. However, because we need to add return_code = x in front of goto each time, there is still a risk of redundancy and forgetting. Therefore, the following macros can be further improved:
# Define RETURN (label, returnCode) {return_code = returnCode; goto label ;}
In this way, we can use RETURN (_ END_F, 2) to set the RETURN value and goto, which simplifies the code and prevents the user from forgetting to set the RETURN value. The final reconstruction result is as follows:
# Define RETURN (label, returnCode) {return_code = returnCode; goto label ;}
Int void f (){
Int return_code = 0;
Char * p1 = (char *) malloc (1024 * sizeof (char ));
Int * p2 = (int *) malloc (10 * sizeof (int ));
...
If (...){
RETURN (_ END_F, 1 );
}
For (...){
If (...){
RETURN (_ END_F, 2 );
}
}
...
_ END_F:
Free (p1 );
Free (p2 );
Return return_code;
}