Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Stack:</strong></p> <ul> <li>Stored in computer RAM just like the heap.</li> <li>Variables created on the stack will go out of scope and are automatically deallocated.</li> <li>Much faster to allocate in comparison to variables on the heap.</li> <li>Implemented with an actual stack data structure.</li> <li>Stores local data, return addresses, used for parameter passing.</li> <li>Can have a stack overflow when too much of the stack is used (mostly from infinite or too deep recursion, very large allocations).</li> <li>Data created on the stack can be used without pointers.</li> <li>You would use the stack if you know exactly how much data you need to allocate before compile time and it is not too big.</li> <li>Usually has a maximum size already determined when your program starts.</li> </ul> <p><strong>Heap:</strong></p> <ul> <li>Stored in computer RAM just like the stack.</li> <li>In C++, variables on the heap must be destroyed manually and never fall out of scope. The data is freed with <code>delete</code>, <code>delete[]</code>, or <code>free</code>.</li> <li>Slower to allocate in comparison to variables on the stack.</li> <li>Used on demand to allocate a block of data for use by the program.</li> <li>Can have fragmentation when there are a lot of allocations and deallocations.</li> <li>In C++ or C, data created on the heap will be pointed to by pointers and allocated with <code>new</code> or <code>malloc</code> respectively.</li> <li>Can have allocation failures if too big of a buffer is requested to be allocated.</li> <li>You would use the heap if you don't know exactly how much data you will need at run time or if you need to allocate a lot of data.</li> <li>Responsible for memory leaks.</li> </ul> <p><strong>Example:</strong></p> <pre class="lang-cpp prettyprint-override"><code>int foo() { char *pBuffer; //&lt;--nothing allocated yet (excluding the pointer itself, which is allocated here on the stack). bool b = true; // Allocated on the stack. if(b) { //Create 500 bytes on the stack char buffer[500]; //Create 500 bytes on the heap pBuffer = new char[500]; }//&lt;-- buffer is deallocated here, pBuffer is not }//&lt;--- oops there's a memory leak, I should have called delete[] pBuffer; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload