Does this type of memory get allocated on the heap or the stack?

Given a slight modification of your example:

class Foo{
    private:
        int x[100];
        int *y;
    public:
        Foo()
        {
           y = new int[100];
        }
        ~Foo()
        { 
           delete[] y; 
        }

}

Example 1:

Foo *bar = new Foo();
  • x and y are on the heap:
  • sizeof(Foo*) is created on the stack.
  • sizeof(int) * 100 * 2 + sizeof(int *) is on the heap

Example 2:

Foo bar;
  • x is on the stack, and y is on the heap
  • sizeof(int) * 100 is on the stack (x) + sizeof(int*)
  • sizeof(int) * 100 is on the heap (y)

Actual sizes may differ slightly due to class/struct alignment depending on your compiler and platform.

Leave a Comment