0
0
Embedded Cprogramming~5 mins

Static memory allocation patterns in Embedded C

Choose your learning style9 modes available
Introduction

Static memory allocation sets aside fixed memory before the program runs. It helps keep memory use simple and predictable.

When you know the exact size of data before running the program.
For storing configuration values that do not change.
When you want fast access to variables without overhead.
In embedded systems with limited memory and no dynamic allocation.
For global variables shared across functions.
Syntax
Embedded C
type variable_name[size];

// Example:
int numbers[10];
char message[20];
Static arrays have fixed size and memory is allocated at compile time.
Memory for static variables remains for the entire program run.
Examples
Declares an integer array of 5 elements with static memory.
Embedded C
int data[5];
Declares a character array with initial text stored in static memory.
Embedded C
char name[15] = "Embedded";
Declares a static integer variable that keeps its value between function calls.
Embedded C
static int counter = 0;
Sample Program

This program uses static memory for an array and a static variable. The array holds fixed numbers. The static variable counts how many times the function runs.

Embedded C
#include <stdio.h>

// Static array with fixed size
int numbers[5] = {10, 20, 30, 40, 50};

// Static variable to count calls
static int call_count = 0;

void print_numbers() {
    call_count++;
    printf("Call %d: ", call_count);
    for (int i = 0; i < 5; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");
}

int main() {
    print_numbers();
    print_numbers();
    return 0;
}
OutputSuccess
Important Notes

Static memory is allocated once and stays until the program ends.

Static variables inside functions keep their value between calls.

Static arrays cannot change size during program execution.

Summary

Static memory allocation reserves fixed memory before running.

Use static arrays and variables when sizes and values are known and fixed.

Static memory is fast and simple but not flexible for changing data sizes.