[libdvdnav-devel] [RFC] Set free'd variables to NULL or not?

Lawrence D'Oliveiro ldo at geek-central.gen.nz
Sat Oct 25 01:00:05 CEST 2014


On Fri, 24 Oct 2014 17:48:19 +0200, Jean-Baptiste Kempf wrote:

> Setting to NULL a variable, after free, is, in the general case,
> wrong and stupid, and error-prone.

I would agree with that.

> However, be careful that, in libdvdread, the variable life-cycle is a 
> bit weird, because of struct re-use and therefore, it avoids crashes.

Let me suggest a convention that I regularly use, that looks something
like this:

    ptr1 = NULL;
    ptr2 = NULL;
    ...
    do /*once*/
      {
         allocate ptr1;
         if (error)
            break;
         allocate ptr2;
         if (error)
            break;
         ...
      }
    while (false);
    free(ptr1);
    free(ptr2);
    ...

Within the do-once, every error condition causes the execution of a
break to cut execution short. But regardless of what happens, allocated
pointers are always freed. This relies on free(3) being an idempotent
operation: namely, freeing a NULL pointer is a no-op.

For a more complex example, see this source file:
<https://github.com/ldo/dvd_menu_animator/blob/master/spuhelper.c>.
This is an extension module for Python. In Python, objects are
reference-counted, so the counts need to be correctly managed. The
Py_XDECREF call takes the place of free; like free, it does nothing if
passed a NULL pointer.

Notice how loops are handled: in several places, you can see a do-once
inside a loop inside a do-once! But now matter how complicated things
get, the permutations of control paths never get out of hand: you can
always trace through them and satisfy yourself that allocated storage
is always correctly freed.


More information about the libdvdnav-devel mailing list