Consider the following snippet:
bool build_regs(int n)
{
REGS *regs = calloc(sizeof(REGS), n);
if (!regs)
return false;
if(!init_regs(regs))
{
free(regs);
return false;
}
if (!check(regs))
{
free(regs); //<-- warning #2116: Local 'regs' is used without being initialized (or using a dangling value).
return false;
}
return true;
}
The compiler doesn't consider that after releasing memory no more code will be executed in this function.
In more complicate functions the noise of warnings would be considerable, unless the code is modified, possibly making it less readable, to avoid the warning.
The workaround, to avoid very complicate if-else nesting is:
bool build_regs(int n)
{
REGS *regs = calloc(sizeof(REGS), n);
if (!regs)
return false;
if(!init_regs(regs))
goto error;
if (!check(regs))
goto error;
return true;
error:
free(regs);
return false;
}
It would be nice if the compiler can consider the end of function (the return) also on variables changes.