1: Sample code that reproduces the problem
unsigned *init(unsigned *p)
{
*p = 42;
return p;
}
unsigned test(void)
{
unsigned *const p = init(&(unsigned){0});
return *p;
}
2: Exact command used to reproduce the problem
sdcc -mz80 --std-c99 --nostdinc -S bug.c -o bug.asm
3: SDCC version tested
SDCC 4.6.4 #17140 (Linux), tested on 8 November 2026.
4: Observed and expected behaviour
test returns 0 instead of 42. This was confirmed by running the generated Z80 code in uCsim.
SDCC initialises the compound literal before calling init, then initialises it again after the call. The second initialisation overwrites the value stored by init. The complete generated body of test is:
_test::
push af
ld hl, #0x0000
ex (sp), hl
ld hl, #0
add hl, sp
call _init
ld hl, #0x0000
ex (sp), hl
ex de, hl
ld e, (hl)
inc hl
ld d, (hl)
pop af
ret
The initialisation of the compound literal must be complete before init is called. Its object remains alive when *p is evaluated in the following statement.
Relevant clauses of C99, as reproduced in N1256:
5: Additional checks
Compiler Explorer comparison: SDCC trunk, SDCC 4.6.0, GCC trunk and Clang trunk.
GCC and Clang at -std=c99 -O2 compile test to return 42. SDCC 4.6.0 emits an invalid ld hl, # instruction for this example, so it is not a passing baseline.
The extra reinitialisation first appears in [r16747], “Fix compound literals in declaration initializers via patch #509 by Howard M. Harte.” I built that revision and its immediate predecessor:
| Revision | Result |
|---|---|
| [r16746] | Emits ld hl, #; assembly fails. |
| [r16747] | Reinitialises the literal after the call; returns 0 in uCsim. |
| [r17140] | Reinitialises the literal after the call; returns 0 in uCsim. |
This identifies the change introducing the extra initialisation, rather than establishing that the example previously worked.
Removing const from the declaration of p does not prevent the extra initialisation. Replacing the body of test with return *init(&(unsigned){0}); produces the expected result, 42. Structure and union compound literals are also affected; explicitly selecting the union member with {.nil = 0} does not generally avoid the bug.
Commit: [r16746]
Commit: [r16747]
Commit: [r17140]
Wiki: SDCC 4.7.0 Release
Attaching a candidate bugfix created using Codex that with need to be reviewed by another developer as per the rules.