Issue
I have the follow test code test.c
:
#include<stdio.h>
int *func()
{
int i = 123;
return &i;
}
int main()
{
printf("%d\n", *func());
}
If I use the command compile it that is OK:
gcc test.c -o test
It will have the follow warning info:
warning: address of stack memory associated with local variable 'i'
returned [-Wreturn-stack-address]
return &i;
^
1 warning generated.
But it can output result: 123
If I use the command:
gcc -Werror test.c -o test
It will have the follow error info:
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 -Werror
option, but I also want to ignore the address of stack memory associated with local variable 'i'
warning, how should I do?
Solution
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.
Answered By - ShadowRanger Answer Checked By - Cary Denson (WPSolving Admin)