c - Why can't get warning information when returning address of local variable use gcc? -


there 2 functions, max1() , max2():

int* max1() {     int a;     int b;      return &a; }  int* max2() {     int a;     int b;      return > b ? &a : &b; } 

we can 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 can nothing when compile max2().

in addition, can warning information clang:

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

thanks , forgive pool english.

in opinion, there's 2 parts question:

  • is compiler always supposed warn every time bad?

no. big no. think of warnings nice friendly note maybe did in trouble. it's no more that: friendly note. nothing in standard says compiler should warn when attempt return pointer local variable. warnings - warnings - (most of them) not strictly required. @ end of day, program going against rules, fault - , job - fix it. there many situations compiler must give error, returning pointers local variables not 1 of them. so, consider lucky warning in first place.

  • should gcc warn in both examples? bug?

for sake of consistency, should. why wouldn't it? if did in similar code, desirable warns in second example. gcc developers interpret bug (that is, bug in whatever code called decide whether spit out warning or not - not bug in core compiler per se).

however, whatever or do, can't rely on compiler warnings being there - nice guy likes give hand once in blue moon. he's not there!

note: apparently, optimizations turned on, gcc more verbose on warnings. try compile optimizations , see happens.


Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -