简体   繁体   中英

C++ code crashes in Win 2000 but does not crash in Win xp

main()
{       
int *p;

free(p);
}

This code crashes in Win 2K. But somehow does not crash in Win Xp! Any idea why?

Edit: Yes. This is a bug and should not be written. Some more info: The compiler used was VC 6 compiler. Compiled the code in release mode on a Win Xp machine. Ran the executable with this code on multiple machines having Win Xp. The code did not result in any crash. But ran the same code on multiple Win 2K machines. It crashed every single time!!

This is Undefined Behavior. It may crash, may not crash, or even draw unicorn on display, there is no rules on how Undefined Behavior behaves.

Your code is Undefined Behaviour: you are trying to use (actually, free) an uninitialized pointer.

Since this is UB, it is totally irrelevant to try and understand why it works (or rather appears to) on one OS but not on the other: the principle of UB is " all bets are off, anything could happen ".

Is that exactly the code as it stands? Ie, nothing in between that initialises p?

As a guess I would say that on your XP system the compiler is initialising p to NULL (I don't think it has to, it just is). On the 2K system the compiler is just adding *p to the stack and the value could be anything.

Free(p) will correctly deal with NULL pointers but if your 2K system hasn't zeroed the pointer when it is created on the stack (which I don't think the C standard requires), then it could be dnagling, and hence free(p) might try to free some arbitrary memory, causing you the problem.

If you start with

int *p = NULL;
free(p);

does this change the behaviour?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM