char c{ 10 };
int* i = (int*)&c;
*i = 1; // Run-Time Check Failure #2 - Stack around the variable 'c' was corrupted.
But I don't get any error in this case
char* c = new char{ 10 };
int* i = (int*)&c;
*i = 1;
//delete c;
Why is it so?
CodePudding user response:
With
int* i = (int*)&c;
you make i
point to the variable c
itself, not where c
is actually pointing.
Thus *i = 1
will change the value of the pointer variable c
not the value of *c
.
If you want to get the same (or similar) behavior you should make i
point to where c
is pointing:
int* i = (int*) c;
As for why it doesn't give you any error, it's because on modern system int
is 32 bits wide, while a pointer (like c
) will be at least 32 bits wide as well (and 64 bits on a 64-bit system).
Lastly a note about doing C-style casts in C : You should always take it as a sign that you're doing something wrong.