我有以下测试代码,文件test.c:
#include <stdio.h>
int *func()
{
int i = 123;
return &i;
}
int main()
{
printf("%d\n", *func());
}
如果我使用命令来编译它,那就没有问题了。
gcc test.c -o test
它会有以下警告信息:
warning: address of stack memory associated with local variable 'i'
returned [-Wreturn-stack-address]
return &i;
^
1 warning generated.
但它可以输出结果:
123
如果我使用命令:gcc -Werror test.c -o test
它将会包含以下错误信息:
error: address of stack memory associated with local variable 'i'
returned [-Werror,-Wreturn-stack-address]
return &i;
^
1 error generated.
我现在想要使用 -Werror 选项,但是我也想忽略 与本地变量 'i' 关联的堆栈内存地址 警告。我该怎么做?
= {0};
初始化结构体/数组时执行),指针所引用的值将不再有效。这个警告是有原因的。 - ShadowRanger-Wreturn-stack-address
是Clang的特性。它在GCC中不存在(除非在GCC 3.4之前已被删除(2003年或更早)-这是非常不可能的)。 - Peter Mortensen