Free variables that are declared inside switch statement blocks
I have a switch statement which declares different variables inside each case block. I want to free these variables at the end of the routine but compiler throw an error that identifier "variable name" is not defined. I do not want to declare these variables before the switch statement. How can I resolve this error? Here is the pseudo code:
int CaseType;
switch(CaseType){
Case 1:
{
double *a = malloc(100 * sizeof(double));
<< some operation here >>
break;
}
Case 2:
{
double *b = malloc(200 * sizeof(double));
<< some operation here >>
break;
}
}
if (CaseType == 1) free(a);
if (CaseType == 2) free(b);
With regard to code like:
case 1:
{
double *a = malloc(100 * sizeof(double));
<< some operation here >>
break;
}
the lifetime of a
is entirely within the block specified by the braces {}
. That object does not exist following that block.
It would be more normal to free the variable within the same scope (ie, immediately before the break
):
case 1: {
double *a = malloc(100 * sizeof(double));
<< some operation here >>
free(a);
break;
}
But, on the off-chance you wanted to use it after that point for something else, you could create the objects before the braces so that they're accessible later, something like:
double *a = NULL, *b = NULL;
switch(CaseType){
case 1: {
a = malloc(100 * sizeof(double));
<< some operation here >>
break;
}
case 2: {
b = malloc(200 * sizeof(double));
<< some operation here >>
break;
}
}
// Do something with a and/or b, ensuring they're not NULL first.
free(a); // freeing NULL is fine if you haven't allocated anything.
free(b);
As an aside, you should always assume that calls subject to failure (like malloc
) will fail at some point and code accordingly. I'll give you the benefit of the doubt that such code exists in the << some operation here >>
section :-)
Variables can only be referenced in the code block they were declared in. Because each of your switch cases has its own block, the pointers cannot be freed from outside that block.
There are a couple of ways you can resolve this. For example you could free the pointers at the end of each switch case (before the break), or you could declare the pointer variable before the switch, that way it can be seen from outside it.
链接地址: http://www.djcxy.com/p/84402.html上一篇: 如何在变量被绕过时使用变量?
下一篇: 在switch语句块中声明的自由变量