Get the value of non-deleted pointers

I am learning OOP and I came across this question:

If we do this:

A* a = new A;

      

operator new

finds space for a variable a

from the heap. I want to know the address where this variable is located.

Question 1

What is the address? What is the difference between the two?

cout <<  a;
cout << &a;

      

Question 2 (main)

Suppose I am doing NOT a delete

pointer. The program will be released. If the pointer was not destroyed by the class destructor, can I return this object using its address (for example, 0x0035fa24) when I run the program again? If so, how?

+3


source to share


5 answers


Question 1

What is the address? What is the difference between the two?

a

- Address of the object. &a

- pointer address.



Question 2 (main)

Suppose I am NOT deleting the pointer. The program will be released. How long since the pointer hasn't been destroyed by the class destructor, can I return it using its address (for example, 0x0035fa24) when I run the program again? If so, how?

A typical modern OS won't let you do this. It will restore memory when the first process exits. No subsequent process will be able to view the contents of the first process memory, as this could be a serious security risk.

+3


source


1:

operator new

finds space for variable a

from heap

No, it is not. The operator new

creates an object of type a

. The variable is then a

initialized with this address.



So, a

evaluates the address where the object lives.

&a

evaluates the address of the variable a.

2: Technically, this is undefined behavior (you will be dereferencing a pointer to an object that doesn't exist). Practically the answer is no. The operating system will free all the memory of your process when it exits.

+2


source


Question 1:

Your variable a

is a pointer. Upon accepting &a

, it issues the address of the pointer itself, not the address where the instance is stored class A

.

Question 2:

No, you cannot do this. There is not a "list of all instances if A" that a machine maintains for you, unless you yourself maintain such a list.

+1


source


Answer to 1: a

will be the address. the operator &

returns the address of what you write later. In plain English, &a

will provide you with the addition of the pointer, a

will be the address stored by the variable a

and *a

will be the content of the addition that it points to a

.

As for 2, I believe it is theoretically possible, but practically impossible.

+1


source


A* a = new A;
cout <<  a;
cout << &a;

      

In the above code snippet, you create a new A on the heap and it is assigned the address a. you then print out the value, this is the address of the dynamically created object. Then you print the address of the pointer itself (on the stack).

And no, you absolutely cannot reclaim lost memory between sessions.

+1


source







All Articles