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.
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.
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.
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.
The reference is stored in a stack while the object is allocated in the heap.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With