I have the following C pseudo code:
int main()
{
int rc = 0;
for (int i = 1; i < 10; i++) {
char *data = malloc(i); // Each iteration has a different alloc size
rc = do_something(data);
if (rc != 0) goto cleanup;
rc = do_something_else();
if (rc != 0) goto cleanup;
cleanup:
free(data);
if (rc != 0) break;
}
return rc;
}
I want to emulate Python's try...finally pattern by breaking out of a loop if a called function returns an error, but only after doing some necessary cleanup work.
So far the code looks OK to me but I'm new to C. Is there a different pattern that avoids the repeated rc != 0 test after free? (I am aware that some people consider goto unconditionally wrong but I see it as the cleanest solution I found for this case.)