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

            Bug ID: 100403
           Summary: Bogus "function may return address of local variable"
                    warning
           Product: gcc
           Version: 10.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: lavr at ncbi dot nlm.nih.gov
  Target Milestone: ---

$ gcc --version
gcc (GCC) 10.2.0


$ cat test.c
#include <stdio.h>
#include <string.h>

#define RECLEN  128


struct R {
    int  head;
    int  code;
    char text[1];
};


const char* fun(int n, const struct R* p)
{
    union {
        struct R r;
        char     rec[RECLEN];
    } x;
    const char* err = 0;

    memset(&x, 0, sizeof(x));
    if (p)
        memcpy(&x.r, p, sizeof(*p));
    else
        err = "Invalid argument";

    if (!err) {
        static const char magic[] = "MAGIC";
        const char* msg;
        if (memcmp(x.rec, magic, sizeof(magic)-1) == 0)
            msg = x.rec;
        else if (x.r.text[0])
            msg = x.r.text;
        else
            msg = "Error w/code";
        if (msg)
            printf("%s\n", msg);
        if (x.rec <= msg  &&  msg < x.rec + sizeof(x))
            err = "Error detected";
        else
            err = msg;
    } else
        printf("%s\n", err);
    return err;
}


$ gcc -Wall -O2 -c test.c
test.c: In function ‘fun’:
test.c:45:12: warning: function may return address of local variable
[-Wreturn-local-addr]
   45 |     return err;
      |            ^~~
test.c:19:7: note: declared here
   19 |     } x;
      |       ^
test.c:19:7: note: declared here


Noted that does not matter whether "sizeof(x)" or "sizeof(x.rec)" is used at
the end of the "if()" statement on line 39.

Reply via email to