Name: Anonymous 2008-04-23 19:14
So when writing C code and you have a function that allocates stuff and other things that needs to be cleaned up, how do you make things not to look like a mess when errors happen? For example (with
There's a lot of repitiion in that. What I'd really want would be something analogous to
What is /prog/'s thoughts on this situation?
return 0 for ok, and return 1 on error)
if ((a = AllocA()) == NULL)
return 1;
if ((b = AllocB()) == NULL) {
FreeA(a);
return 1;
}
if (SomeInit() != INIT_OK) {
FreeA(a);
FreeB(b);
return 1;
}
while (something) {
if (error) {
FreeA(a);
FreeB(b);
SomeCleanup();
return 1;
}
}
if (tarballs) {
FreeA(a);
FreeB(b);
SomeCleanup();
return 1;
}
return 0;There's a lot of repitiion in that. What I'd really want would be something analogous to
atexit() for the current scope. The only way that doesn't repeat all that I've thought of is through goto like
if ((a = AllocA()) == NULL)
return 1;
if ((b = AllocB()) == NULL)
goto free_a;
if (SomeInit() != INIT_OK)
goto free_b;
while (something) {
if (error)
goto free_all;
}
if (tarballs)
goto free_all;
return 0;
free_all: SomeCleanup();
free_b: FreeB(b);
free_a: FreeA(a);
return 1;What is /prog/'s thoughts on this situation?