Copy .data and Zero .bss Correctly in Your Reset Handler
Copy .data from flash and zero .bss in a Cortex-M reset handler without bugs: alignment, the memset trap, empty sections and a debugger check to run.

Two loops decide whether every global variable in a firmware image has the value C promises: one that copies .data from flash to RAM, and one that zeros .bss. They are four lines each, and they are wrong in the field more often than their size suggests. The usual failures are a copy that reads past the end because a symbol is not aligned, a clear loop that the compiler quietly turns into a call to memset, and an off-by-one in the end condition that leaves one word stale. This post writes both loops for a Cortex-M4 with arm-none-eabi-gcc 13.2, explains what each line protects against, and shows how to verify the result from the debugger before you trust it.
What the language requires
C says a static or global variable with an initialiser starts with that value, and one without an initialiser starts as zero. On a hosted system the loader does that. On a microcontroller your reset handler is the loader. The linker puts initialised variables into .data and zeroed ones into .bss, and gives you symbols marking where each section begins and ends, as covered in the post on writing a linker script. The reset handler's job is the mapping from those symbols to memory contents:
| Section | In flash image | At run time | Handler does |
|---|---|---|---|
.data | Initial values, at _sidata | Lives in RAM, _sdata to _edata | Copy flash to RAM |
.bss | Nothing | Lives in RAM, _sbss to _ebss | Write zeros |
The simple version
The standard loops use uint32_t pointers and the linker symbols:
#include <stdint.h>
extern uint32_t _sidata, _sdata, _edata, _sbss, _ebss;
static void init_ram(void)
{
uint32_t *src = &_sidata;
uint32_t *dst = &_sdata;
while (dst < &_edata)
*dst++ = *src++;
dst = &_sbss;
while (dst < &_ebss)
*dst++ = 0;
}This is correct if three things hold. All four boundary symbols are 4-byte aligned (the linker script uses ALIGN(4) around each section), the sections are in RAM and flash as the script says, and the compiler emits exactly these loops.
The comparison dst < &_edata handles the empty section. When there is no initialised data, _sdata equals _edata and the loop runs zero times. Writing the condition as do ... while or comparing with != would run once or forever.
Why the symbol type matters
The linker script defines _sdata as an address with no associated size or type. C code declares it as extern uint32_t _sdata and takes its address. Declaring it as extern char _sdata[] and indexing is equally valid. What is not valid is reading the variable's value, which dereferences whatever lives at that address.
The pointer type decides the step. With uint32_t *, each dst++ advances four bytes, and the loop condition compares addresses. If the script left a boundary unaligned, say because a 2-byte variable ended the section, the final word write would overrun by two bytes into a neighbouring section. The . = ALIGN(4) before _edata = . in the script pads to a multiple of four so the word loop stops exactly.
The memset trap
GCC has an optimisation called loop distribution (-ftree-loop-distribute-patterns) that recognises a loop writing zeros and replaces it with a call to memset. It is enabled at -O2 and above in current GCC releases, and on some versions at -O3 only. In a reset handler this is a bug: memset is a function in the C library that may use initialised globals, may be placed in a section the handler has not copied yet, and in the worst case recursively calls back into code that expected zeroed memory.
You can see the effect by compiling the example at -O2 and disassembling:
arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -O2 -c reset.c -o reset.o
arm-none-eabi-objdump -d reset.o00000000 <init_ram>:
0: b538 push {r3, r4, r5, lr}
...
1c: f7ff fffe bl 0 <memset>A bl memset inside init_ram is the signature. The exact instructions vary with compiler version and flags; the call is what to look for. The fix is to forbid the transformation on the function:
__attribute__((optimize("no-tree-loop-distribute-patterns")))
static void init_ram(void)or to compile the startup file with -fno-tree-loop-distribute-patterns. The same transformation can turn the copy loop into memcpy, so the attribute covers both. A freestanding build (-ffreestanding) does not prevent it: the GCC documentation says calls to memcpy, memmove, memset and memcmp may be generated even then.
An alternative is to make the loops opaque to the optimiser by writing through a volatile pointer. That blocks the pattern at the cost of slower, word-by-word stores that the compiler may not combine. For a reset handler the cost is small and the guarantee is simple.
static void zero_bss(void)
{
volatile uint32_t *p = &_sbss;
while (p < &_ebss)
*p++ = 0;
}A faster loop, safely
Copying word by word is correct but slow on a part with a large .data. If the boundaries are 8-byte aligned, you can copy doublewords with uint64_t, but only if the Cortex-M's load and store of a 64-bit value compiles to ldrd and strd, which are available on Armv7-M and require only 4-byte alignment. The gain is real but small, and the cost is more places for an alignment bug. For most firmware the simple loop is the right choice, and you only optimise when a profile of boot time shows the copy.
On parts with a DMA controller, a memory-to-memory DMA transfer can copy .data while other early setup runs, but it needs the DMA clock enabled and a transfer configured before the copy it is replacing. That trade is rarely worth the code.
Several regions
Some parts have more than one RAM region that needs initialisation, such as CCM or backup SRAM on STM32. The vendor pattern is a table of copy and zero ranges that the linker script fills, so the handler loops over table entries and needs no change when a section is added:
struct copy_entry { uint32_t *src, *dst, *end; };
struct zero_entry { uint32_t *begin, *end; };
extern const struct copy_entry __copy_table_start[], __copy_table_end[];
extern const struct zero_entry __zero_table_start[], __zero_table_end[];
static void init_tables(void)
{
for (const struct copy_entry *e = __copy_table_start; e < __copy_table_end; e++) {
uint32_t *s = e->src, *d = e->dst;
while (d < e->end)
*d++ = *s++;
}
for (const struct zero_entry *e = __zero_table_start; e < __zero_table_end; e++) {
for (uint32_t *d = e->begin; d < e->end; d++)
*d = 0;
}
}The linker script emits the tables with LONG(LOADADDR(.data)) LONG(ADDR(.data)) LONG(ADDR(.data) + SIZEOF(.data)) in a .copy.table section. CMSIS defines the same idea in its startup code for some Arm cores, using __copy_table_start__ names. The details, including the exact names, differ by vendor, so confirm against your script.
Checking it in the debugger
A bug here shows up as variables holding wrong values only occasionally, so make the check explicit. Add two canaries:
int initialised = 0x5A5A5A5A;
int zeroed;Break at the first line of main and print them:
(gdb) print/x initialised
(gdb) print/x zeroed$1 = 0x5a5a5a5a
$2 = 0x0If initialised is wrong, the copy is broken or _sidata points to the wrong flash address. If zeroed is non-zero on a warm reset, the clear loop did not run or ran short, because RAM keeps its contents across a soft reset. Test with a warm reset on purpose: a cold power-up on many parts leaves RAM mostly zero, which hides this bug.
Then compare symbol addresses to the map, using arm-none-eabi-nm -n firmware.elf | grep -E ' _s?(data|bss|idata)| _e(data|bss)':
08001bb8 D _sidata
20000000 D _sdata
20000014 D _edata
20000014 B _sbss
20000060 B _ebssThe _edata and _sbss match because .bss follows .data. The addresses here are an example.


