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.
Just that a jump to reset may fail spectacularly - lots of startup code is written based on the assumption that the processor comes from a real reset. With just a jump to the reset vector, then timers, interrupts sources etc might already be up and spinning. After the fake-reset, the code can then get hammered by "impossible" interrupts.
Anyway - people should try to program by contract. So staying away from constructs where there doesn't exist an explicit contract promising a specific behaviour. And people should try and give some of the promises from the compiler vendor a bit less weight than they do, and try more to just follow the language standard instead of making use of a compiler-specific feature. Unless, of course, that compiler-specific feature really is important for the specific target platform.
I said "You, as the creator of the system, should do something appropriate. Like fall through to code that triggers a watchdog reset."
Is there any question about that? I hope nobody would be foolish enough to argue against it.
Except in cases where randomly resetting equipment isn't seen as a solution, but rather could create some even more dangerous situations to arise. In those cases I'd generally argue against it.
Sometimes it's appropriate to shutdown into a safe state and sound an alarm.
Blanket statements of what something should do, without really thinking it through, are a bit asinine.
You, as the creator of the system, should do something appropriate
Absolutely. As should all aspects of a system being created.