Or You Could Simplify The Error-Recovery Paths
Or You Could Simplify The Error-Recovery Paths
Posted Dec 25, 2014 21:19 UTC (Thu) by ldo (guest, #40946)Parent article: The "too small to fail" memory-allocation rule
I have written a lot of code according to the following paradigm:
ptr = NULL;
... similarly initialize any other pointers ... do /*once*/
{ ...
allocate ptr;
if (failure)
break;
...
futher processing, including further pointer allocations as necessary
...
} while (false);
free(ptr);
... free any other allocations ...
This kind of thing makes it easy to convince yourself, by visual inspection, that the allocated storage will be freed once, and only once, no matter what control path is taken. A key simplifying point is that the free(3) call is idempotent: freeing a NULL pointer is a no-op.
If you want to see a more elaborate example, including loops and nested do-once-within-do-once, have a look at this spuhelper.c Python extension module.