Why can't I get warning information when returning the address of a local variable 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 compiling max1 () using 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 when compiling max2 (), we can't get anything.

In addition, we can receive warning information on 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.

      

Thank you very much and forgive me for my english.

+3


source to share


1 answer


In my opinion, there are two parts to this question:

  • Is the compiler always supposed to warn you every time you do something bad?

Not. Big no. Think of warnings as a friendly note that you may have done something to get you in trouble. But that's nothing more: a friendly note. Nothing in the standard says that the compiler should warn you when you try to return a pointer to a local variable. Most warnings are just warnings - but (most of them) are not strictly required. At the end of the day, your program goes against the rules, so it's your mistake - and your job - to fix it. There are many situations where the compiler should give an error, but returning pointers to local variables is not one of them. So, consider that you are lucky enough to receive this warning in the first place.

  • Should gcc warn you in both examples? This is mistake?


For consistency, this should be. Why not? If it has been done in similar code, it is probably desirable for it to warn in the second example. This is probably what the gcc devs interpret as a bug (i.e. a bug in what code is called to decide whether to spit out this warning or not, but is not a bug in the main compiler).

However, no matter what you say or do, you just can't rely on the compiler warnings that are always there for you - they're just that cute guy who loves to give you his hand one day in a blue moon. He's not always there!

NOTE . Apparently when you enable optimizations, gcc is usually more verbose for warnings. Try compiling optimized and see what happens.

+1


source







All Articles