Memory
Stack Vs Heap
Stack variables are automatic local objects, while heap objects are requested and released explicitly.
stack value
`stackValue` is a normal local variable with automatic lifetime.
heap value
`malloc` creates heap storage that must later be released with `free`.
Stack Vs Heap
stack_vs_heap.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int stackValue = 4;
int *heapValue = (int *)malloc(sizeof(int));
if (heapValue == 0) {
return 1;
}
*heapValue = stackValue + 1;
printf("stack=%d heap=%d\n", stackValue, *heapValue);
free(heapValue);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int stackValue = 7;
int *heapValue = (int *)malloc(sizeof(int));
if (heapValue == 0) {
return 1;
}
*heapValue = stackValue + 1;
printf("stack=%d heap=%d\n", stackValue, *heapValue);
free(heapValue);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int stackValue = 10;
int *heapValue = (int *)malloc(sizeof(int));
if (heapValue == 0) {
return 1;
}
*heapValue = stackValue + 1;
printf("stack=%d heap=%d\n", stackValue, *heapValue);
free(heapValue);
return 0;
}
stackValue ← 4, heapValue ← ⟨addr A⟩
4int main(void) {5 int stackValue→ 4 = 4; //@stackValue=7, 106 int *heapValue→ ⟨addr A⟩ = (int *)malloc(sizeof(int));78 if (heapValue == 0) {9 return 1;10 }1112 *heapValue⟨addr A⟩ = stackValue4 + 1;1314 printf("stack=%d heap=%d\n", stackValue4, *heapValue⟨addr A⟩);15 free(heapValue⟨addr A⟩);16 return 0;17}outputstack=4 heap=5
stackValue ← 7, heapValue ← ⟨addr A⟩
4int main(void) {5 int stackValue→ 7 = 7;6 int *heapValue→ ⟨addr A⟩ = (int *)malloc(sizeof(int));78 if (heapValue == 0) {9 return 1;10 }1112 *heapValue⟨addr A⟩ = stackValue7 + 1;1314 printf("stack=%d heap=%d\n", stackValue7, *heapValue⟨addr A⟩);15 free(heapValue⟨addr A⟩);16 return 0;17}outputstack=7 heap=8
stackValue ← 10, heapValue ← ⟨addr A⟩
4int main(void) {5 int stackValue→ 10 = 10;6 int *heapValue→ ⟨addr A⟩ = (int *)malloc(sizeof(int));78 if (heapValue == 0) {9 return 1;10 }1112 *heapValue⟨addr A⟩ = stackValue10 + 1;1314 printf("stack=%d heap=%d\n", stackValue10, *heapValue⟨addr A⟩);15 free(heapValue⟨addr A⟩);16 return 0;17}outputstack=10 heap=11