Write an example that properly handles 5 different mallocs within the same function and properly cleans up after itself on failure without using goto's. Here's the goto example:
Resources *Resources_alloc(void)
{
Resources *ret;
if (NULL == (ret = malloc(sizeof(Resources))))
goto FAIL;
if (NULL == (ret->rsrc1 = malloc(sizeof(ret->rsrc1))))
goto FAIL_RESOURCES;
if (NULL == (ret->rsrc2 = malloc(sizeof(ret->rsrc2))))
goto FAIL_RSRC1;
if (NULL == (ret->rsrc3 = malloc(sizeof(ret->rsrc3))))
goto FAIL_RSRC2;
if (NULL == (ret->rsrc4 = malloc(sizeof(ret->rsrc4))))
goto FAIL_RSRC3;
assert(ret);
goto END;
/* error handling and return */
FAIL_RSRC3:
free(ret->rsrc3);
FAIL_RSRC2:
free(ret->rsrc2);
FAIL_RSRC1:
free(ret->rsrc1);
FAIL_RESOURCES:
free(ret);
ret = NULL;
FAIL:
assert(!ret);
END:
return ret;
}
Also, it isn't always the case that the thing you need to reclaim is a pointer and can be dynamically tested as to whether it was successfully acquired or not. For example, you can't test a pthread_mutex_t to see if it is valid or not. Your code has to know either based on its structure (i.e. - like the above) or you have to have a separate tracking variable per such object.
PS - Yes, the example is a bit contrived, there'd be little reason to malloc those members rather than just have them allocated as part of the Resources struct. I just did that as an illustrative example. Also, I'd typically cast the result of a malloc to the appropriate type so that a C++ compiler wouldn't complain about my code, but I haven't specified their types in this example.