You are here:   Home >> Program >> Stack vs. Heap

Stack vs. Heap

Here is a simple rule when to define objects on the heap and when to do it on the stack.

The stack is much more efficient than the heap.

Simple rule: Use the stack when you can.

You cannot use the stack if you need the object in other functions. (Stack allocations are deleted when the function that allocated them returns.)

You cannot use the stack if you need a variable size. Stack allocations use a constant size that must be known at compile time.

When you define an object (class instance) on the stack, it is automatically deleted (its destructor is called) when the class instance goes out of scope.

Instead, when you allocate on the heap, you must pay attention to properly cleanup the object (else you will have memory or resources leaks).

For example:

<code>

  // ** Stack Allocation **
  {
      // Allocate MyClass instance on the stack
      MyClass c;

      … use c

  } // c destructor called by C++ compiler

  // ** Heap Allocation **
  {
      // Allocate on the heap
      MyClass * ptrC = new MyClass();

      …use heap-allocated instance
      ptrC->DoSomething(…);

  } // Destructor *not* called here! Memory leak!
   // Must do an explicit delete ptrC;

</code>

However, if you use smart pointers, like boost:: or tr1:: shared_ptr, you can safely allocate on the heap, and let the smart pointer pay attention to free the object it is referencing. (So, with shared_ptr, you can safely allocate on the heap, and kind of “forget” about freeing the object. It’s kind of C# or Java garbage collection…)

Recently, Visual C++ Team released a kind of “Service Pack 0” for VS2008, which includes the useful shared_ptr class, and also other great things. I recall that David C. posted the link on this newsgroup recently. You can read something also here:

http://blogs.msdn.com/vcblog/archive/2007/12/26/just-what-is-this-tr1…

In general, if you have a small objects, you can allocate on the stack. Instead, if you want to allocate big memory, you should allocate on the heap (the stack is a limited resource, more limited than the heap).

Note also that there are classes like C++ STL container classes (e.g. std::vector) that you allocate on the stack. But the class implementation internally can allocate the required memory on the heap, e.g.:

  std::vector< double > someData(1000);

The vector class instance (‘someData’) is allocated on the stack (so you don’t have to call its destructor explicitly), but the vector data (the 1000 double values) is allocated on the heap internally by std::vector implementation.

Referrence:

Permalink: Code Library » https://www.ucosoft.com/stack-vs-heap.html

Related Posts

One response to “Stack vs. Heap”

  1. […] post “Stack vs. Heap“, we have discussed about stack and heap, and given the simple rules on the choice of stack […]

Leave a Reply

Your email address will not be published. Required fields are marked *