Code Examples
Take a look at some code and analyze how the allocations on the stack and the heap take place.
We'll cover the following...
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 ...