I came across this code in an interview.
int main()
{
int **p;
p = (int **) new int(7);
cout<<*p;
return 0;
}
I was expecting some run time error at *p. But when I ran the code , it executed successfully with output “0x7”. Can someone please explain me how is this working. Thanks.
The proper answer would be None of the above unless you are given some extra constraints. Basically the code is allocating an
intand interpreting that memory as if it was anint*(through areinterpret_cast). The first problem is that, being areinterpret_cast, the result is unspecified in the general case, and if the size ofintis smaller than the size ofint*(think a 64bit architecture) the result is undefined behavior as you are reading beyond the size allocated in thenewcall.