Search⌘ K

Code Examples

Understand stack and heap memory allocation through practical C code examples. Learn how local variables are created and removed on the stack, and how dynamic memory allocation on the heap works with pointers. This lesson helps you visualize memory management in C and sets the foundation for understanding pointers and dynamic memory usage.

We understand how stack and heap work in theory. Now, let’s internalize this by looking at concrete examples.

A stack allocation example

Here is a short program that creates its variables on the stack. It looks like the other programs we have seen so far.

C
#include <stdio.h>
double multiplyByTwo(double input) {
double twice = input * 2.0;
return twice;
}
int main(void)
{
int age = 30;
double salary = 12345.67;
double myList[3] = {1.2, 2.3, 3.4};
printf("Your doubled salary is %.3f\n", multiplyByTwo(salary));
return 0;
}

Let’s visualize how the variables are created and removed from the stack as the program statements are executed.

Variables declared in main are allocated on the stack before it is invoked
1 / 9
Variables declared in main are allocated on the stack before it is invoked

  • On lines 10, 11 and 12, we declare two variables of ...