Allocating memory for objects

When we instantiate a C ++ variable as int x

inside a function (i.e. x is a local variable), it is allocated on top of the process stack. But if we do int *x= new int

, the space is provided on the heap.

So my questions are:

  • How about objects of different classes (classes provided by C ++ or user defined)? Where are their objects created? For example: Let Employee be a class and we are declaring Employee emp;

    . Where emp

    is space-> set on the stack or heap?

  • If the declaration int a[4]

    is inside a function, do all four cells from a

    get space on the stack?

+3


source to share


5 answers


  • It depends. If it Employee

    has members that are allocated only on the stack, then the entire object. BUT, Employee

    they can have pointer elements, and the constructor Employee

    can allocate memory for them on the heap. Then some of the members are on the heap and some are on the stack.

  • Yes.



+2


source


All local variables, whether they come from built-in types from classes or arrays, are on the stack. All dynamic allocations are on the heap.

Of course, modifiers such as static

for a local variable will cause the variable to be placed somewhere else, so it persists between function calls.

Also, to confuse you further, when you create a local pointer variable and point to a dynamically allocated object, eg.

Class* a = new Class;

      



The actual variable a

is on the stack, but the memory it points to is on the heap.


Appendix: The C ++ spec doesn't actually mention anything about the stack or heap, just the behavior of different types of variables.

+7


source


This is exactly the same as with regular types.

Class a; //stack. Usage: a.somethingInsideOfTheObject
Class *a = new Class(); //heap. Usage: a->somethingInsideOfTheObject

      

Note that if the class itself allocates something on the heap, that part will always be on the heap, for example:

class MyClass
{
public:
    MyClass()
    {
        a = new int();
    }
private:
    int * a;
};

void foo()
{
    MyClass bar;
}

      

in this case the variable bar

will be allocated on the stack, but a

internally it will be allocated on the heap.

+5


source


User-defined classes (and types) are indistinguishable from built-in types. So

Employee emp; // allocated in stack
Employee* emp = new Employee(); // allocated in heap

      

Regarding your second question, local arrays are allocated on the stack

Employee emp[4]; // 4 instances on stack

      

+2


source


Typically, if the compiler knows about it at compile time (i.e. local variables), it is on the stack.
If the compiler doesn't know about it at compile time (ie, dynamic allocation through new

, malloc

etc.), It is on the heap.

This post has a detailed explanation: global-memory-management-in-c-in-stack-or-heap

+1


source







All Articles