Stack errors during debugging
<Stack is not available: Cannot access memory at address 0xXXXXXXXX.>
This sort of error is normally caused by stack corruption, or by having an incorrectly defined System stack.
The error occurs when the debugger is trying to walk the stack to show the stack frames and values of local variables. The debugger has found (or calculated) a value on the stack that is outside of memory and when it tries to access that location, it is getting an error.
Bear in mind that the stack is not constratined in size (there is no hardware to warn you if the stack grows 'too large' - overflows the space you have allocated for it). This means that you have to make sure that the space used for the stack is large enough, and is allocated in a place where it will not overwrite something else. The stack is not only required for your application code, but also for (possibly nested) interrupts.
The initial stack pointer is defined at address zero of the vector table. When the processor resets, it loads the stack pointer from address zero (and the PC from address 4).
There are (at least) 2 ways to allocate the stack. You need to look at the startup code to determine which method your code is using. The 2 standard methods of defining the stack are:
- place the stack at the top of memory
- based on vStackTop, which is defined in the linker script
- define a (fixed size) array in memory
- e.g. unsigned int stack[STACK_SIZE];
If you use the vStackTop method, this means the stack will start there and grow 'down'. The heap (for 'malloc' etc) will be placed after your data section and grow 'up'. If you are not careful, the stack and the heap will 'meet' somewhere and start overwriting each other. It is my guess that this is happening.
If you use the 'array in memory' allocation, you need to increase the amount of memory pre-allocated for the stack to ensure it is large enough - but bear in mind that it can overflow that into whatever is allocated 'before' the stack.
Making sure the stack is large enough is an inexact science and often is determined by trial and error. If you are constrained on RAM space, and need a more scientific method of calculating the stack, you will need to examine your code to determine the max potential depth of function calls together with the number of potential nested interrupts and calculate the stack size required.