cancel
Showing results for 
Search instead for 
Did you mean: 

STM32F10X - Stack gets corrupted by using big variables/arrays/structs

bernhard
Associate II
Posted on March 14, 2014 at 16:02

1.  Everything normal

0690X000006056YQAQ.png

2. Already strange behaviour. Stack size doesn't increase although test3 is one Byte larger 

0690X00000604n8QAA.png

3. Same here, stack doesnt grow

0690X00000604aOQAQ.png

4. Stack is corrupted (with test 3 being 232 Bytes large)

0690X000006056XQAQ.png

5. Stack is corrupted with large arrays

0690X000006057pQAA.png

I'm on a STM32F103RB - so I should have 20kBytes of RAM. Can anybody explain what's happening here and how I'm able to fix that?

How do I set the LDFLAGS without having a makefile?

#stm32f10x #stack-size #bug #stack #heap
12 REPLIES 12
Posted on March 15, 2014 at 13:50

Indeed, but I think the exercise here was to understand the observed behaviour, and where the stack size was defined.

Yes, being in main() would compound the issue, given that it never leaves and the stack allocation for the local/auto variables is thus rather permanent.

In the general case however having several KB of stack space for temporary variables, and totally avoiding the use of dynamic allocation, or large global ones, is not necessarily unreasonable. Where issues really come up is when PC programmers, used to vast/endless stacks, allocate massive structures on the stack, or utilize recursion.

It is important to consider stack depth, and call tree implications, and balance the use of global allocations against ones that are only temporal in nature.
Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
Posted on March 15, 2014 at 19:41

''Prefixing them with the ''static'' keyword will move them to the heap''

No, it won't.

The heap is used by malloc() for dynamic allocation!

''but bear in mind they'll keep their value through successive runs of the function''

Correct.

''That is to say, if function ''foo'' has a static int which it sets to 123, when it's run again, that value will be pre-set to '123' again''

A point of clarification:

If the value is set by the initialiser  in the definition, it is only applied once - at startup. If the function then modifies the value, it is the modified  value that will still be there the next time the function is entered.

''As a bonus, the linker will complain if you try to allocate more variables than you have available heap memory''

Again, the heap is used for runtime dynamic  allocation - so the Linker can't warn about that. But it can  warn about variables declared as 'static'.

Posted on March 17, 2014 at 20:37

''To be honest, you really shouldn't be allocating variables as large as that on the stack''

Why not?

''The total size of those is going to be several kilobytes!''

Which is not a problem provided  you have a suitably-sized stack...