有兩個函數,最大值1()和最大值2():爲什麼在返回局部變量的地址時使用gcc時不能得到警告信息?
int* max1()
{
int a;
int b;
return &a;
}
int* max2()
{
int a;
int b;
return a > b ? &a : &b;
}
當編譯最大值1()使用gcc我們可以得到警告信息:
[email protected]:~/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;
^
但是,我們可以得到什麼時,編譯MAX2 ()。
另外,我們可以通過鐺得到警告信息:
[email protected]:~/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.
非常感謝,並原諒我的英語池。
非常類似於[沒有編譯器警告,用於返回引用局部變量](http://stackoverflow.com/q/29872531/1708801) –
我真的不知道爲什麼,兩者都返回一個局部變量地址。也許是一個錯誤?你使用的是哪個版本的gcc? – LPs
這看起來像上面問題中提到的相同的錯誤,如果我們使用更新版本的[gcc與優化打開](http://coliru.stacked-crooked.com/a/6def165f938615b8)它拾起第二種情況。 –