#include <iostream>
int main() {
int x = 0;
int* p1 = new(&x) int[2]; // 2 integers allocated at &x
// the first one will overwrite x's value?
// what about the second int
*p1 = 5;
*(p1 + 1) = 6;
system("PAUSE");
}
you forgot to include <new> in the first and last samples, however; the 4 source codes are the same :D, I just want to know why the compiler says that there is a corruption around x.
+ Exception thrown : Run-Time Check Failure #2 - Stack around the variable 'x' was corrupted. occurred
-- This happens when going out of scope --
1 2 3 4 5 6 7 8
#include <iostream>
int main() {
int x = 0;
auto a = new(&x) int[2];
a[0] = a[1] = 5;
std::cout << a[0] << ' ' << a[1] << '\n';
system("PAUSE"); // It will crash after you press any key
}
Instead of allocating memory you use the memory of x. So the second field of the array is out of bounds, i.e. undefined behavior which might lead to a crash,
I'm not sure what you mean by "Autos" there (or why you would think I would know what that means), but I assume it's some kind of debugging thing in VS.
But the reason for the exception is obvious. I thought that was the point of your question. You aren't providing enough space for the two-int array. How could it possibly fit into the space of one int? What did you expect to happen?
The only reason the other code "crashes" is because there is apparently a special check that is done at the end of your code that (attempts to) detect stack corruption. You are probably running it in some kind of debugging mode. If you run it in a "release" mode, it may not actually crash. The fact is that there is almost certainly space for the extra int on the stack, so it's the kind of error that can go undetected without a special check.
If you only modify the first int of the two then the special (presumably debug-only) check won't be able to detect a problem.
You could try leaving it in the debugging mode and not writing to either of the locations and just doing the cout statement to see what value it prints. I wish I had a windows system to test it on myself. I'm thinking of getting one. :-)