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"