How to avoid long chain of free’s (or deletes) after every error check in C?

You could define a new label that would free the resources and then you could GOTO it whenever your code fails.

char* function()
{
    char* retval = NULL;
    char* mem = get_memory(100);  // first allocation
    if (!mem)
        goto out_error;

    struct binder* b = get_binder('regular binder');  // second allocation
    if (!b)
        goto out_error_mem;

    struct file* f = mk_file();  // third allocation
    if (!f)
        goto out_error_b;

    /* ... Normal code path ... */
    retval = good_value;

  out_error_b:
    free_binder(b);
  out_error_mem:
    free(mem);
  out_error:
    return retval;
}

Error management with GOTO was already discussed here:
Valid use of goto for error management in C?

Leave a Comment