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 int
and interpreting that memory as if it was an int*
(through a reinterpret_cast
). The first problem is that, being a reinterpret_cast
, the result is unspecified in the general case, and if the size of int
is smaller than the size of int*
(think a 64bit architecture) the result is undefined behavior as you are reading beyond the size allocated in the new
call.
You create a new int and initialize it with value 7.
int *x = new int(7);
You than cast it to a pointer (eg memory address 7 or 0x07)
int **p = (int**) new int(7);
Then you show this address with cout.
*p is equal to (int*)7
It's a pointer with value 7.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With