Reputation: 61
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.
Upvotes: 3
Views: 143
Reputation: 21213
In my opinion, there's 2 parts to this question:
No. Big no. Think of warnings as a nice friendly note that maybe you did something that will get you in trouble. But it's no more than that: a friendly note. Nothing in the standard says that the compiler should warn you when you attempt to return a pointer to a local variable. Most warnings are just that - warnings - but (most of them) are not strictly required. At the end of the day, your program is going against the rules, so it is your fault - and your job - to fix it. There are many situations where a compiler must give an error, but returning pointers to local variables is not one of them. So, consider yourself lucky to get that warning in the first place.
For the sake of consistency, it should. Why wouldn't it? If it did in similar code, it is probably desirable that it warns in the second example. It is probably something that gcc developers interpret as a bug (that is, a bug in whatever code is called to decide whether to spit out that warning or not - but not a bug in the core compiler per se).
However, whatever you say or do, you simply can't rely on compiler warnings always being there for you - they are just that nice guy who likes to give you a hand once in a blue moon. He's not always there!
NOTE: Apparently, with optimizations turned on, gcc is usually more verbose on warnings. Try to compile with optimizations and see what happens.
Upvotes: 1