Course contentsShow
← Embedded Systems & Computer Architecture
Lesson 227 of 9363. Microcontroller Fundamentals and Bare-Metal CFree lesson

Implementing Zero-Initialization for Uninitialized Data

Learners will define the .bss section to ensure uninitialized variables are cleared to zero by the startup code during system boot.

Implementing Zero-Initialization for Uninitialized Data

In this lesson, you will learn how to configure your linker script and startup code to ensure that all uninitialized global and static variables are automatically reset to zero when your microcontroller boots up.

The Role of the .bss Section

In C, global and static variables that are not explicitly initialized are placed in a special memory segment called the .bss section (short for "Block Started by Symbol"). Unlike initialized variables (which reside in the .data section and store specific starting values in Flash), the .bss section does not contain actual data. Instead, it simply reserves a block of RAM.

Because RAM contains random electrical noise upon power-up, you cannot assume these variables start at zero. To maintain predictable system behavior, your startup code must manually clear this memory region before the main() function is ever called.

Defining and Clearing .bss

First, you define the .bss section in your linker script to group these variables. You must provide the start and end addresses so the startup code knows where to work:

.bss : {
    _sbss = .;         /* Start address of .bss */
    *(.bss)            /* All .bss sections from object files */
    *(COMMON)          /* Common symbols */
    _ebss = .;         /* End address of .bss */
} > RAM

Next, in your assembly or C startup file, you perform the "zero-init" loop. You point a pointer to _sbss and write zeros to memory until you reach _ebss:

extern uint32_t _sbss, _ebss;

void clear_bss(void) {
    uint32_t *ptr = &_sbss;
    while (ptr < &_ebss) {
        *ptr = 0;
        ptr++;
    }
}

This simple routine ensures that every time your system resets, your global state starts from a clean, known zero-value, preventing unpredictable bugs caused by residual garbage data in RAM.

Key Takeaway: The .bss section defines a block of RAM that must be explicitly cleared to zero by your startup code to guarantee a deterministic system state.