r/cprogramming • u/BitOfAZeldaFan3 • Jan 20 '26
Initializing array crashes program
I'm running into a strange issue with my baremetal ARM project. I'm cross compiling with clang on WSL. I know baremetal programming is a little over my head but it's my special interest right now and I have to roll with it.
Initializing an array like this causes the program to crash and jump to 0x200:
uint32_t array[5] = { 1, 2, 3, 4, 5 };but declaring and later assigning doesn't crash:
uint32_t array[5];
array[0] = 0;
array[1] = 1;
...
array[4] = 5;Same with strings. char str[] = "hellorld"; crashes but char* str "hellorld"; doesn't.
Arrays above a certain size, like
int array[10] = { 1, 2, 3, 4, 5};fails to link with a "ld.lld: error: undefined symbol: memset" error.
I would never be so bold as to claim a compiler bug, but the memory layout shouldn't differ. My stack isn't overflowing. Using __attribute___((aligned(n))) doesn't fix it for any value of n.
Is there some quirk to array initialization in C? I was under the impression that it was natively supported in all versions of C. Is this a consequence of compiling with -nostdlib?
15
u/cryptic_gentleman Jan 20 '26
It’s likely because, in freestanding C, some of the runtime functionality isn’t present so initializing an array via arr[5] = {…} isn’t possible because this sort of assignment statement is relying on memcpy in the background to copy the values from .rodata into the array which isn’t directly available in a freestanding/bare metal environment. The char str[] crashes for the same reason but char *str works because the compiler knows to just write the bytes to the location pointed to by *str. As for why arrays above a certain size cause a crash I’m not sure but I believe it’s related to the first issue.
1
u/BitOfAZeldaFan3 Jan 20 '26
For what it's worth, here's some disassembly:
1
u/Daveinatx Jan 20 '26 edited Jan 20 '26
Have you dumped and grep'd the program and all includes (if any)? Otherwise, have you disabled optimization?
Your disassembly looked as expected. It leads me to think a dependency is getting picked up elsewhere, bare metal or not.
Edit: I think
ldneedsmemset.. Try implementing your own and see what happens.3
u/SauntTaunga Jan 20 '26
Shouldn’t linking fail if memcpy() and memset() are missing?
1
u/DunkingShadow1 Jan 20 '26
Did you include stdlib?
2
u/daydrunk_ Jan 20 '26
Statically compile if you are on bare metal.
1
u/Alive-Bid9086 Jan 20 '26
I usually write
const int arr[] = {1, 2, 3, 4, 5};
0
u/[deleted] Jan 20 '26
[deleted] — view deleted comment