A variable created on the heap, 2 pointers pointing to the same variable have different addresses?

I just found out the difference between stack and heap. After creating a function that will dynamically allocate memory on the heap for me, I return a pointer and display (in and out of the function) the address and value of each pointer.

The values ​​are the same as expected, but the addresses of the same piece of memory on the heap are different, which I did not expect.

Why? Should pHeap2 and pTemp indicate the same address?

#include <iostream>
using namespace std;

int* intOnHeap(); // returns an int on the heap
int main()
{
 int* pHeap = new int; // new operator allocates memory on the heap and returns its address
       // 'new int' allocates enough memory on heap for one int and returns the address on the heap for that chunk of memory
       // 'int* pHeap' is a local pointer which points to the newly allocated chunk of memory
 *pHeap = 10;
 cout << "*pHeap: " << *pHeap << "\n\n";

 int* pHeap2 = intOnHeap();
 cout << "pHeap2:\n-----------" << endl;
 cout << "Address:\t" << &pHeap2 << "\n";
 cout << "Value:\t\t" << *pHeap2 << "\n\n";

 cout << "Freeing memory pointed to by pHeap.\n\n";
 delete pHeap;

 cout << "Freeing memory pointed to by pHeap2.\n\n";
 delete pHeap2;

// get rid of dangling pointers
    pHeap = 0;
    pHeap2 = 0;

 system("pause");
 return 0;
}

int* intOnHeap()
{
 int* pTemp = new int(20);
 cout << "pTemp:\n-----------" << endl;
 cout << "Address:\t" << &pTemp << "\n";
 cout << "Value:\t\t" << *pTemp << "\n\n";
 return pTemp;
}

Output:

*pHeap: 10

pTemp:
-----------
Address:        0042FBB0
Value:          20

pHeap2:
-----------
Address:        0042FCB4
Value:          20

Freeing memory pointed to by pHeap.

Freeing memory pointed to by pHeap2.

Press any key to continue . . .
+3
source share
3 answers

, , . , pTemp pHeap2; , . & pTemp pHeap2, .

:

0042FBB0           0042FBC0     0042FCB4
------------       ------       ------------
| 0042FBC0 |------>| 20 |<------| 0042FBC0 |
------------       ------       ------------
pTemp                           pHeap2

&pTemp is 0042FBB0 &pHeap2 is 0042FCB4. , pTemp pHeap2 (, run ), & pTemp pHeap2, 0042FBC0 .

+5

, pTemp pHeap2 . &pTemp &pHeap2 . , & . , pTemp int, &pTemp int.

+1

&pHeap2does not return the value of the pointer, it returns the address of the pointer. This is because &, in this context, means "address".

i.e. on 0042FCB4 in memory there is a pointer pointing to 0042FBB0 (i.e. in a large-end environment, you will see 00 42 FB B0 at 0042FCB4).

0
source

Source: https://habr.com/ru/post/1777256/


All Articles