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

            Bug ID: 110267
           Summary: Bogus warning "function may return address of local
                    variable"
           Product: gcc
           Version: 12.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: nullplanwichmann at web dot de
  Target Milestone: ---
              Host: x86_64-pc-linux-gnu
            Target: x86_64-pc-linux-gnu
             Build: x86_64-pc-linux-gnu

Minimal test case:
extern char *strdup(const char *);
extern int fill(char *);
char *do_something(char *buf)
{
  char tmp[10];
  if (!buf)
    buf = tmp;
  int rv = fill(buf);
  if (rv < 0) return 0;
  if (buf[0] != '/')
    return 0;
  return buf == tmp? strdup(buf) : buf;
}

Compile with -O2 -Wall. All GCC versions I have tried (10.2.1-6 from an old
Debian installation, 12.2.0 from current Debian stable, and a development
snapshot I compiled from git this morning) warn:

tmp.c: In function ‘do_something’:
tmp.c:13:1: warning: function may return address of local variable
[-Wreturn-local-addr]
   13 | }
      | ^
tmp.c:5:8: note: declared here
    5 |   char tmp[10];


The warning is of course wrong: Whenever buf == tmp, the function returns the
strdup() of tmp, not tmp itself. I was resigned to assume that gcc cannot
identify that this is the case, but I noticed that if the if-selection in lines
10-11 is removed, then the warning disappears. The warning only occurs when
optimizing at level s, 2, or 3.

Additionally, the old gcc version 10.2.1-6 mangled the warning output, it would
write out:

cc1: warning: function may return address of local variable
[-Wreturn-local-addr]
tmp.c:5:8: note: declared here
    5 |   char tmp[10];

As if that was some internal warning. That seems to be fixed in the newer
versions, though.
  • [Bug c/110267] New: Bogus warn... nullplanwichmann at web dot de via Gcc-bugs

Reply via email to