Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objects on the heap and references

While answering this question I got a bit confused. We all know that this works fine due to the C++ copy semantics:

int *some_obj = new int(42);
int a_copy = *some_obj;

delete some_obj;

printf("The answer is %d\n", a_copy);

But what about this?

int *some_obj = new int(42);
int& a_ref = *some_obj;

delete some_obj;

printf("The answer is %d\n", a_ref);

Is this accessing deleted memory?

Probably asked various times in various forms, but this is not very Google friendly. Hell, I couldn't make a decent title.

like image 470
orlp Avatar asked Jun 30 '12 07:06

orlp


People also ask

Where are the references to the heap objects are stored?

Heap space is used for the dynamic memory allocation of Java objects and JRE classes at runtime. New objects are always created in heap space, and the references to these objects are stored in stack memory. These objects have global access and we can access them from anywhere in the application.

Do object references live on the heap?

All objects in Java are stored on the heap. The "variables" that hold references to them can be on the stack or they can be contained in other objects (then they are not really variables, but fields), which puts them on the heap also.

When an object is created both reference and object are stored on heap?

Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution. Whenever an object is created, it's always stored in the Heap space and stack memory contains the reference to it.

Are references on the stack or heap?

The reference is stored in a stack while the object is allocated in the heap.


1 Answers

Yes, it is. So that's not permitted. (You can ensure you see the difference by using a class with a destructor that changes the value.)

like image 103
David Schwartz Avatar answered Sep 28 '22 05:09

David Schwartz