7

I am using ARM-GCC compiler and I found on Internet two versions for the startup_stm32f10x_cl.c file (startup code). The processor is: STM32F105RC (ARM Cortex M3).

Common part :

#define STACK_SIZE       0x100 /*!< The Stack size */
__attribute__ ((section(".co_stack")))
unsigned long pulStack[STACK_SIZE];    

Then, the first version starts the vector table like this:

void (* const g_pfnVectors[])(void) =
{       
  (void *)&pulStack[STACK_SIZE],     /*!< The initial stack pointer           */
  Reset_Handler,                /*!< Reset Handler                            */
...

while the second version looks like this:

void (* const g_pfnVectors[])(void) =
{       
  (void *)&pulStack[STACK_SIZE - 1],     /*!< The initial stack pointer           */
  Reset_Handler,                /*!< Reset Handler                            */
    ...

So, my question is:
Which one is the correct stack pointer initialization?

3
  • As long as they both result in correctly aligned addresses with writeable memory below them, it doesn't really matter unless you're trying to squeeze every last byte of RAM out of the thing. Commented Oct 22, 2015 at 10:41
  • @Notlikethat: So, what you're saying is that in the second version there are 4 bytes left off (unused). Is it (maybe) a common practice to have some sort of safety-guard memory area in such circumstances? Commented Oct 22, 2015 at 11:51
  • I wouldn't say there's much safety in it (that example could just be down to someone not being sure if a stack push is post-decrement or pre-decrement), but there's nothing to prevent you having some fixed global storage area above the stack if you really want, or starting the stack and heap in the middle of RAM growing away from each other Itanium style, or anything else ;) Commented Oct 22, 2015 at 12:24

1 Answer 1

8

From ARM documentation for M3 cores instruction-set:

PUSH uses the value in the SP register minus four as the highest memory address

and

On completion, PUSH updates the SP register to point to the location of the lowest stored value

So, my interpretation is that the starting point of SP must be +4 of the highest address, i.e. the address immediately after the Stack array bounds. Hence

(void *)&pulStack[STACK_SIZE]

looks right, as that address (although not part of the array), will never be used.

2
  • what is the array 'pulStack'?
    – K.Mulier
    Commented Jan 22, 2017 at 17:55
  • 2
    the name it's hungarian-notation (check it on google) for an array holding unsigned longs... it can be seen as a pointer to unsigned long vector (p u l). It's merely the memory placeholder, the sort of "this space is taken" definition, for the compiler to use to store the stack.
    – jpinto3912
    Commented Jan 24, 2017 at 22:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.