[Bug middle-end/94527] RFE: Add an __attribute__ that marks a function as freeing an object

msebor at gcc dot gnu.org gcc-bugzilla@gcc.gnu.org
Wed Apr 8 16:28:05 GMT 2020


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94527

Martin Sebor <msebor at gcc dot gnu.org> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|NEW                         |ASSIGNED
   Target Milestone|---                         |11.0
           Assignee|unassigned at gcc dot gnu.org      |msebor at gcc dot gnu.org
                 CC|                            |msebor at gcc dot gnu.org

--- Comment #7 from Martin Sebor <msebor at gcc dot gnu.org> ---
I've actually been experimenting with this for GCC 11 as an extension of
detecting uninitialized reads from dynamically allocated storage.  My initial
approach is to

1) add a second (optional) argument to attribute malloc to mention the
deallocation function (e.g., free for calloc, malloc, strdup, etc., or fclose
for fopen and fdopen)
2) add the free function attribute as described in comment #0

Besides (or instead of just) detecting uninitialized reads from allocated
storage this approach detects all accesses to freed pointers the same way
-Wreturn-local-addr detects returning addresses of auto variables (i.e., not
just dereferences of the pointers but also plain reads).  In addition, it
detects invalid pairs of calls (such as the free(fopen (...) kind, or the
similar C++ new/delete mismatch), as well as attempts to free pointers known
not to have been returned from an allocation function at all (e.g., pointers to
VLAs or those returned from alloca()).

An interesting question is what to do about functions like freopen and realloc.
 It seems that both would have to be decorated with attribute free as well as
attribute malloc, suggesting that to be fully general, attribute malloc might
need to reference at least two and possibly an arbitrary number of deallocation
functions to pair with each allocation function.

As Jon notes, there are also APIs that operate on non-pointer types.  For
those, a separate pair of analogous attributes like acquire and release might
be appropriate.

So unless someone else is much farther along into a prototype I'll assign this
to myself.


More information about the Gcc-bugs mailing list