s***i 发帖数: 49 | 1 int * var = new int;
*var=5; |
k***r 发帖数: 4260 | 2 heap vs stack?
【在 s***i 的大作中提到】 : int * var = new int; : *var=5;
|
l*****d 发帖数: 359 | 3 auto variable (life time from definition to end of block) vs. dynamic allocated variable (you control the life time)
【在 s***i 的大作中提到】 : int * var = new int; : *var=5;
|
c**m 发帖数: 30 | 4 depending on where the lines appear:
a:
int *p1 = new int;
int p2 = 5;
int main() {}
Then both p1,p2 are some space reserved in data segment, but p1's address
may have more requirements such as alignment since it's a pointer. p2's
value is stored as 5, however p1's value is inited with an address in heap
by calling alloc during static initialization before main is called.
b:
void foo()
{
int *p1 = new int;
int p2 = 5;
...
}
p1,p2 could be space reserved on stack or simply registers. p2 could b |
c**m 发帖数: 30 | 5 and of course if you don't delete p1, you have memory leak. :) |
l*****d 发帖数: 359 | 6 it's about the memory p1 pointed to and p2, not p1 and p2.
【在 c**m 的大作中提到】 : depending on where the lines appear: : a: : int *p1 = new int; : int p2 = 5; : int main() {} : Then both p1,p2 are some space reserved in data segment, but p1's address : may have more requirements such as alignment since it's a pointer. p2's : value is stored as 5, however p1's value is inited with an address in heap : by calling alloc during static initialization before main is called. : b:
|
c**m 发帖数: 30 | 7 that's obvious.
but question asks for difference behind the scene, no mention of anything
specific about memory p1 pointed to and p2 (candidate is supposed to figure
that out). and there're very big differences depending on where they appear
. besides, there's nothing stopping me from making var a pointer to an
integer at location 5:
int var =5;
*((int*)var) = 5;
also, I always thought sizeof(int) == sizeof(void*) but apparently not
because visual studio 64-bit sizeof(int) == 4 and sizeof(voi
【在 l*****d 的大作中提到】 : it's about the memory p1 pointed to and p2, not p1 and p2.
|