Why the code below doesn't generate "segmentation fault" on windows?
#include <st开发者_Go百科dio.h>
#include <string.h>
void bad() {
printf("Oh shit really bad~!\r\n");
}
void foo() {
char overme[4] = "WOW";
*(int*)(overme+8) = (int)bad;
}
int main() {
foo();
}
In 32bit linux it generates segmentation fault,but in windows not.Why?
Because undefined behaviour means exactly that: undefined. Not defined-but-will-cause-error, but undefined, meaning that anything can happen.
And sometimes that anything may be that it works as expected. That doesn't make it a good thing, of course, since it may stop working as expected with a new compiler or operating system or runtime library or even based on the day of the week or phase of the moon.
The ISO standards mandate how a well defined program will behave, they do not mandate how an undefined one will, other than to say it can do anything it darn well pleases.
For the specific case, you would have to examine the assembler code generated by the compiler to see why it's not trashing your stack. It's possible that Linux stores a rather vital piece of information at the location you're overwriting (like the return address from main
) while Windows stores something relatively benign (like the return code from main
).
精彩评论