Why can’t get warning information when returning address of local variable use gcc?

There are two functions, max1() and max2():

int* max1()
{
    int a;
    int b;

    return &a;
}

int* max2()
{
    int a;
    int b;

    return a > b ? &a : &b;
}

We can get warning information when compile max1() use gcc:

king@king:~/temp$ gcc test1.c
test1.c: In function ‘int* max()’:
test1.c:6:9: warning: address of local variable ‘a’ returned [-Wreturn-local-addr]
 int a;
     ^

But we can get nothing when compile max2().

In addition, we can get warning information by clang:

king@king:~/temp$ clang test1.c
test1.c:9:21: warning: address of stack memory associated with local variable 'a' returned
      [-Wreturn-stack-address]
    return a > b ? &a : &b;
                ^
1 warning generated.

Thanks very much and forgive my pool English.


Source: gcc

Leave a Reply