Object Creation on the Stack/Heap

Object creation on the stack/heap?

Actually, neither statement says anything about heap or stack. The code

Object o;

creates one of the following, depending on its context:

  • a local variable with automatic storage,
  • a static variable at namespace or file scope,
  • a member variable that designates the subobject of another object.

This means that the storage location is determined by the context in which the object is defined. In addition, the C++ standard does not talk about stack vs heap storage. Instead, it talks about storage duration, which can be either automatic, dynamic, static or thread-local. However, most implementations implement automatic storage via the call stack, and dynamic storage via the heap.

Local variables, which have automatic storage, are thus created on the stack. Static (and thread-local) objects are generally allocated in their own memory regions, neither on the stack nor on the heap. And member variables are allocated wherever the object they belong to is allocated. They have their containing object’s storage duration.

To illustrate this with an example:

struct Foo {
Object o;
};

Foo foo;

int main() {
Foo f;
Foo* p = new Foo;
Foo* pf = &f;
}

Now where is the object Foo::o (that is, the subobject o of an object of class Foo) created? It depends:

  • foo.o has static storage because foo has static storage, and therefore lives neither on the stack nor on the heap.
  • f.o has automatic storage since f has automatic storage (= it lives on the stack).
  • p->o has dynamic storage since *p has dynamic storage (= it lives on the heap).
  • pf->o is the same object as f.o because pf points to f.

In fact, both p and pf in the above have automatic storage. A pointer’s storage is indistinguishable from any other object’s, it is determined by context. Furthermore, the initialising expression has no effect on the pointer storage.

The pointee (= what the pointer points to) is a completely different matter, and could refer to any kind of storage: *p is dynamic, whereas *pf is automatic.

Why do we need to create an object in heap?

In practice the call stack is limited and small. The typical limit is a few megabytes. In contrast, you could often allocate gigabytes in heap memory.

(on some systems, you might configure the system to have a larger stack; but you need to tell your users if you need that)

Also, and most importantly, the call stack is a stack, so has a LIFO (last in first out) discipline. In many cases, you want to release objects in an order unrelated to their allocation or just in a "first allocated, first destroyed" order (and that is impossible on a stack).

Consider reading something about garbage collection, e.g. the GC handbook. It teaches you useful concepts and terminology about dynamic memory allocation (even for C programs with manual memory management). Read also about the virtual address space of your process (se also this answer, at least for Linux).

Another advantage of dynamic memory allocation is that the same executable can run on various computers (with various resources, in particular different amount of RAM), but won't be able to process the same amount of data. If you had to allocate all the memory statically, this would not be the case (e.g. a C program with 50 gigabytes of static data could not even start on my laptop).

Object creation on Heap

If we talk about only your code, then there is only one Manager object, and there will be constructor-chaining till Object class. Apart from this object there will be other objects also which are needed by JVM to run your program, these will be class objects, method objects which are currently loaded in to run your program.

For more details about the execution order of any program, to get more understanding, please read once below link,

https://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.1.1

Objects on a stack vs Objects on a heap in C++

Objects on the stack have the really neat property that the memory that backs them is automatically freed at the end of that stack frame (e.g. when the function returns.) C++ extends this concept by also calling destructors for all stack objects whenever they fall out of scope (i.e. they're still freed in the case that an exception is thrown before the function returns.) Since this makes memory management dead simple, and memory management errors have the frustrating combination of being easy to make and hard to detect, stack allocation should be preferred whenever it is feasible.

The downside of stack-allocated objects is...well...they're deleted when the function returns. Sometimes there are legitimate reasons to want the object to live longer. In those cases, you have no choice but to allocate from the heap.

Another point to consider is that stack allocation pretty much has to be a size that is known at the time the software is compiled (but see alloca function available on some platforms.) There are a ton of real world scenarios where you won't know until the program is running how much memory you need. Take for example an address book application. If I am coding such an application, I obviously have no idea how many people the end user is going to want in their address book. The user has to tell the program this information. In this case, you need to have dynamically allocated memory, so you're again looking at heap allocation.

Object methods stored in stack or heap?

Will explain based on how it works in Java.

Methods and variables(inside methods) are stored in the stack.

Local variables (variables inside methods) are stored in the stack. But not the method itself.

By method, we refer to the behaviour or the list of instructions that needs to be executed. This does not vary every method call and not even vary for every object instance created. The behaviour remains the same at the class level.

The behaviour is stored in a region called Method area. You can refer Java Spec for more details.

As per spec,

The method area is created on virtual machine start-up. Although the method area is logically part of the heap, simple implementations may choose not to either garbage collect or compact it. This version of the Java Virtual Machine specification does not mandate the location of the method area or the policies used to manage compiled code.

It is left to the JVM implementation on where the method area is located.

Implementations like HotSpot VM, until Java 7, used to store the method area as part of the heap. But from Java 8, it is moved out of heap and the space allocated for heap is not consumed by the method area.

What happens to for example the constructor?

Constructions are methods with a special name called, <init>.1. They are stored in the same way as other methods.

As a side note, there is a class initialization method, called <clint>, which handles static block in class.2

What is The difference between creating constructor in heap or in stack?

Although in both cases abc is in the automatic memory (commonly called "stack") it is not the same kind of object:

  • In the first example abc is a pointer, which is stored on the stack. However, there is a second object of type myclass which is stored in dynamic memory (commonly called "heap"). Object pointer abc points to the object in the heap.
  • In the second example abc is of type myclass. This is the only object being created.

Main difference between the two approaches is that an object created in dynamic memory can "outlive" the function inside of which it is created. When the pointer abc goes out of scope, its heap object remains active. For example, you can return it from a function without making a copy.

Where does a stack object inside a heap allocated object gets allocated in c++?

The pointer to the object, called myObj in your program, is created on the stack.

The object itself B() is created on the heap. width and height are contained within the memory taken up by B() and are thus also on the heap.

In Ascii Art:

Stack --- myObj
|
Heap [ B -- A [ Width, Height ] ]


Related Topics



Leave a reply



Submit