1
int *p1=10;

and

int *p2;
p2=new int;
*p2=10;

What is the difference between these two variables? Aren't both the variable allocated in the heap?

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
user1247347
  • 201
  • 2
  • 4
  • 5

4 Answers4

4

The difference is that the first one doesn't compile:

lol.cpp:2:10: error: cannot initialize a variable of type 'int *' with an rvalue of type 'int'
    int *p1 = 10;
         ^    ~~
1 error generated.

whereas the second one makes an int on the heap with value 10, and allocates a pointer to that value on the stack.

If the first one did compile, say if you added a cast, it'd be assigning the value 10 to the pointer p1, meaning that p1 would point to the memory address 10 = 0x0A, and *p1 would try to dereference that address as an int, which would be a segfault. (If you used a different number that happened to land within your process's memory space, it'd be some arbitrary integer based on what the contents of the memory contained.)

Danica
  • 28,423
  • 6
  • 90
  • 122
  • Is that Clang? I congratulate you on your excellent compiler choice :) +1 as it's correct too. –  Mar 03 '12 at 21:32
1

And according to another part of your question. No, they are not both allocated on the heap. In fact they are both allocated on the stack. Only the second one points to a region allocated on the heap by new operator. They would be allocated on the heap, if they were part of an object being allcated with new.

mip
  • 8,355
  • 6
  • 53
  • 72
0

The expression int* p1 = 10 should not compile: it initializes a pointer with an integer!

ppaulojr
  • 3,579
  • 4
  • 29
  • 56
Emilio Garavaglia
  • 20,229
  • 2
  • 46
  • 63
0

Both p1 and p2 are pointers to integer variables.

The initialization of p1 is wrong. As a pointer it should contain the address of an integer variable. And you are assigning the "address" a value of '10': you are setting it to point to address 0x0000000A, which is almost certainly invalid.

James
  • 24,676
  • 13
  • 84
  • 130
user1192525
  • 657
  • 4
  • 20