Skip to content

Instantly share code, notes, and snippets.

@xpcoffee
Last active August 29, 2015 14:08
Show Gist options
  • Save xpcoffee/60263aa987d5f7747ec7 to your computer and use it in GitHub Desktop.
Save xpcoffee/60263aa987d5f7747ec7 to your computer and use it in GitHub Desktop.
Stack vs Heap

####Stack vs Heap in C-languages

Stack
A stack is memory set aside for running code. Typically, calls to functions create temporary variables.
These variables are stored on the stack.

Stacks are a LIFO (last in, first out) structure.

Heap
The heap is used for dynamic memory allocation.
It has no particular order and so is more difficult to manage than the stack.

Example
Non-dynamic variables are created on the stack:

{ // new block of code
  int age = 4;
} // age is on stack, will go out of scope here and be de-allocated

Dynamic variables are created on the heap. In C:

int *age = malloc(sizeof(int));
*age = 4;
// -- do things --
free(age);

In C++:

Age *age = new Age(4);
// -- do things --
delete age;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment