Stack memory

  • Sprouting
  • c.

Stack memory is used for storing static data of a known, fixed size. It operates on last-in, first-out (LIFO) principles in strict sequence. Because stack memory is highly organised, and lives in CPU caches, operations are much faster than heap memory operations.

Allocation and deallocation is automatically managed by the CPU and takes only a single instruction (moving the stack pointer). Stack memory is typically used for fixed-size structures, local variables, and primitive data types.

Example

A fixed-size array is automatically allocated memory on the “stack” in a C program. When the main function ends, the fixed-size array is automatically deallocated as it goes out of scope.

#include <stdio.h>
int main()
{
int arr[3] = {16, 32, 64};
printf("arr[1] address: %p, value: %d\n", (void *)&arr[1], arr[1]);
return 0;
}

Backlinks