At the beginning of main I have two variables, namely:
unsigned char audioDataBuffer1[512]; unsigned char audioDataBuffer2[512];
Later in the code I use them as buffers for audio data from SD Card.
The problem is that the stack pointer is set too low and these big variables overwrite my stack pointer which is set automatically by Keil startup code. How is this possible?
I have noticed that the problem disappears when I set above variables to global, or when I use malloc instead.
I would appreciate if you could explain what goes wrong here and is there any reason I should not declare large variables like this?
Thank you.
The stack allocation is often made in startup.s (or equivalent), a stack with 0x200 bytes clearly wouldn't be adequate if your variables a auto/local in nature. If you don't want them on the stack, define them globally, or use static declaration.
Placing variables on the stack is a good thing for variables with a limited life span, when the life spam can be matched by call tress.
Dynamic allocation is suitable when the variables have limited lifte span but the life span is hard to match to call trees. Or when the system at runtime have to decide how to slice the memory, i.e. how much memory to spend on different information.
If the goal is just to hide the variables from the global namespace, then it is often better to make them static.
Many architectures have more limitations for use of stack space than for global variable address range, so there should always be a bit of extra thought before placing large variables on the stack. If nothing else, large stack variables are likely to trip any other developer who comes later and have to take over the code.
A local function can have variables of limited size. For best utilization of stack we should avoid structures and arrays of larger size defining in the local function. Instead declare them as global variables. I have faced a similar issue , I have declared an array of 2000 Bytes for a local variable in a function. When i call that function these bytes gets corrupted at some point. Later i have made the array as global and everything works fine. I have found in some text that arrays and structures of more length should not be declared as local variables.