I know its to do with compiler optimization, but I am looking for a real deep dive into how/why and how to ensure i am notified of this behaviour in real code.
I have this code
void swap(char *s)
{
strcpy(s, "nope!");
printf("Result: %s\n", s);
};
void main(){
...
swap("this should segfault");
...
}
obviously, it should segfault, but visual studio in release mode reduces it down to just inlining the printf.
This seems like the kind of thing that could really bite me in the ass later, so i would love it if you could shine some light on this for me.
for completeness sake here is the expected assembly
push offset s ; "this should segfault"
call j_?swap@@YAXPAD@Z ; swap(char *)
and here is the generated assembly
push offset s ; "this should segfault"
push offset Format ; "Result: %s\n"
call ds:__imp__printf
and here are the compiler options as requested in comments
/GS /GL /analyze- /W3 /Gy /Zc:wchar_t /Zi /Gm- /O2 /Fd"Release\vc120.pdb" /fp:precise /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /Gd /Oy- /Oi /MD /Fa"Release\" /EHsc /nologo /Fo"Release\" /Fp"Release\scratchpad2.pch"
sfor anyone but you to know that for sure. Is it null? Is it a buffer overflow?shold. And if they don't hold (as in,sdoesn't point to a large enough writable buffer), then the code exhibits undefined behavior, and the compiler is free to produce any outcome. "Appears to work" is one possible manifestation of undefined behavior.expected assembly: push offset sbut there is no symbolsat that point insidemain.sis fromswap(char* s). it is compiled using platform toolset v120 using default options for release mode