Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit casting of ptr to "ptr to a ptr"

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.

like image 657
Forever Learner Avatar asked Apr 15 '12 18:04

Forever Learner


2 Answers

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.

like image 144
David Rodríguez - dribeas Avatar answered Oct 20 '22 07:10

David Rodríguez - dribeas


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.

like image 35
gulyan Avatar answered Oct 20 '22 07:10

gulyan