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

            Bug ID: 83648
           Summary: missing -Wsuggest-attribute=malloc on a trivial
                    malloc-like function
           Product: gcc
           Version: 8.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: msebor at gcc dot gnu.org
  Target Milestone: ---

The malloc() function returns a non-null pointer on success and null on
failure.  Thus, a function that returns the result of malloc can be consider
"malloc-like."  Likewise, a function the either returns the result of malloc or
a null pointer is itself also trivially malloc-like.

The -Wsuggest-attribute=malloc option is supposed to issue warnings for
malloc-like functions that would benefit from being declared with attribute
malloc.  The following test case shows that GCC issues the warning for the
first kind of function but not for the second.  The second kind is likely to be
defined to avoid the non-portable/underspecified malloc behavior with a zero
argument (malloc can return either a non-derefernceable pointer to a distinct
object or null).

$ cat a.c && gcc -O2 -S -Wall -Wsuggest-attribute=malloc a.c
void* f (unsigned n)   // -Wsuggest-attribute=malloc (good)
{
  return __builtin_malloc (n);
}

void* g (unsigned n)   // missing -Wsuggest-attribute=malloc
{
  return n ? __builtin_malloc (n) : 0;
}

a.c: In function ‘f’:
a.c:1:7: warning: function might be candidate for attribute ‘malloc’ if it is
known to return normally [-Wsuggest-attribute=malloc]
 void* f (unsigned n)   // -Wsuggest-attribute=malloc (good)
       ^

Reply via email to