...

/

Code Examples

Code Examples

Let's look at some code and analyze how the allocations on stack and the heap take place.

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.

Press + to interact
#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.

Press + to interact
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 ...