http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57587

            Bug ID: 57587
           Summary: RFE: 'maybenull' attribute.
           Product: gcc
           Version: 4.8.0
            Status: UNCONFIRMED
          Severity: enhancement
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: dwmw2 at infradead dot org

I'd like an attribute analogous to __attribute__((nonnull)) for function
arguments, except that it should indicate that an argument is *expected* to be
NULL. Or preferably, it could be applied to a *type* or a function member...

It is common, in glib-based software, to have functions which return
success/failure and also take an *optional* 'GError **' argument which can be
populated with more detailed error information on failure. This error pointer
is usually passed through to inferior functions, and a failure of such a
function will cause the parent function to immediately return 'FALSE', with the
detailed error having already been populated.

However, the 'error' argument may often be NULL, if a failure is not going to
be reported to the user.

It is a common bug, when such a function calls another function, to use the
'error' function to detect whether an error happens — instead of checking the
return value of the function as we should. To make that slightly clearer...

This code bad:

gboolean my_foo(GError **error)
{
    my_bar(error);
    if (*error)
       return FALSE;

    return my_baz(error);
}

This code good:

gboolean my_foo(GError **error)
{
    if (!my_bar(error))
    return FALSE;

    return my_baz(error);
}

This bug is distressingly common. There may be other ways to catch this common
coding error, but if we could ensure that the compiler would *warn* about any
untested assumption that the pointer is non-NULL, that would be useful.

Having it done along the lines of the __attribute__((nonnull)) function
attribute may be simpler, but it would require every function declaration to
carry the attribute. And if we could rely on codemonkeys do to that, we could
probably rely on them to get it right in the first place.

So if there's a way we can mark the *GError* type with an attribute that says
"pointers to this are probably NULL", that would be useful. I'm not entirely
sure how that would work.

It might also be useful to mark struct members with the same attribute. The
definition of 'struct foo' would effectively be able to enforce the rule "Thou
shalt not assume that foo_s->bar is non-NULL. Always check before dereferencing
it".

Reply via email to