Reputation: 1877
I have the following test code, file test.c:
#include <stdio.h>
int *func()
{
int i = 123;
return &i;
}
int main()
{
printf("%d\n", *func());
}
If I use the command to compile it that is OK,
gcc test.c -o test
It will have the following warning information:
warning: address of stack memory associated with local variable 'i'
returned [-Wreturn-stack-address]
return &i;
^
1 warning generated.
But it can output the result: 123
If I use the command:
gcc -Werror test.c -o test
It will have the following error information:
error: address of stack memory associated with local variable 'i'
returned [-Werror,-Wreturn-stack-address]
return &i;
^
1 error generated.
Now I want to use the -Werror option, but I also want to ignore the address of stack memory associated with local variable 'i' warning. What should I do?
Upvotes: 5
Views: 15282
Reputation: 242
According to the gcc documentation about -Werror
, you can "negate -Werror
for specific warnings" with -Wno-error=
. In our case, we can ignore -Wreturn-stack-address
-Wno-error=return-stack-address
as follows:
gcc -Werror -Wno-error=return-stack-address test.c -o test
As already stated another answer here, you can disable most warnings by appending no-
to the warning name. In the documentation linked above:
Each of these specific warning options also has a negative form beginning
-Wno-
to turn off warnings; for example,-Wno-implicit
."
I recognize that the example given is this question is just an example. Places where I've needed this are from compiling external libraries that I cannot edit, due to licensing or other reasons. Often, I can put in a ticket to remove the warning, but in the meantime, I assess the risk and choose to silence the warning until an update comes.
Upvotes: 0
Reputation: 155438
Most gcc
warnings can be disabled by prefixing the name of the warning with no-
, e.g. -Wno-return-stack-address
.
That said, this is not something you want to ignore; returning pointers to stack variables is undefined behavior, and while it has semi-predictable results on most compilers, it's incredibly fragile; any function call at all, implicit or explicit, could stomp on the value that pointer is referencing.
Upvotes: 12