Stack Vs Heap
Stack | Heap |
---|---|
The OS allocates the stack for each system-level thread when the thread is created. | Usually the OS is called by the language runtime to allocate the heap |
The stack is attached to a thread | The heap is allocated at application startup by the runtime |
The size of the stack is set when a thread is created. | The size of the heap is set on application startup, but it can grow as space is needed |
The stack is faster | Slower, much more complex bookeeping |
Variables created on the stack will go out of scope and automatically deallocate. | Variables on the heap must be destroyed manually |
Stores local data, return addresses, used for parameter passing | Used on demand to allocate a block of data for use by the program |
Example
int foo() { char *pBuffer; //-nothing allocated yet bool b = true; if(b) { //Create 500 bytes on the stack char buffer[500]; //Create 500 bytes on the heap pBuffer = new char[500]; }//buffer is deallocated here, pBuffer is not }//oops there's a memory leak, I should have called delete[] pBuffer;