Memory
Stack Vs Heap
Stack variables are automatic local objects, while heap objects are requested and released explicitly.
Stack Vs Heap
stack_vs_heap.c
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int stackValue = ;
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 = ;
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 = ;
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;
}
stack value
`stackValue` is a normal local variable with automatic lifetime.
heap value
`malloc` creates heap storage that must later be released with `free`.