Skip to main content
DavidAlfa
Senior II
July 3, 2021
Question

Compiler not checking ram overflow in local variables?

  • July 3, 2021
  • 7 replies
  • 1321 views

Stm32CubeIDE v1.6.1

STM32 F1 library v1.8.4

New, empty project.

Something simple as this comples without any error or warning in a stm32f103.

It has 20KB ram, but for some reason the compiler doesn't care that I'm allocating 64KB!

Of course, it causes a hard fault. Declaring variable as global throws an error like it should.

void test(void){
 volatile uint8_t dat[65536];
 for(uint32_t t=0;t<sizeof(dat);t++){
 dat[t]=GPIOA->IDR;
 }
 for(uint32_t t=0;t<sizeof(dat);t++){
 GPIOB->ODR=dat[t];
 }
}

This topic has been closed for replies.

7 replies

Nikita91
Lead II
July 3, 2021

The compiler checks errors at compile time. So if you declare a variable as global it is allocated at compile time.

A local variable is allocated at run time from the stack. The compiler can't check this.

DavidAlfa
DavidAlfaAuthor
Senior II
July 3, 2021

So the only way is to use malloc and check for a valid pointer?

This variable is overwriting other existing memory! There's no way to check this at compile time?

TDK
July 3, 2021

You can use the stack analyzer in STM32CubeIDE to verify you're within whatever limit you set.

There's no runtime specific check that can be done here.

0693W00000BcjmAQAR.png 

The call graph based usage is especially useful:

0693W00000BcjmFQAR.png

"If you feel a post has answered your question, please click ""Accept as Solution""."
TDK
July 3, 2021

> So the only way is to use malloc and check for a valid pointer?

Malloc uses the heap, while defining a local variable uses the stack. They are different pools, but share the same space. Even if you get a valid pointer back from malloc, it could still be overwriting variables on the stack.

"If you feel a post has answered your question, please click ""Accept as Solution""."
DavidAlfa
DavidAlfaAuthor
Senior II
July 3, 2021

Yes, I can see the local cost. But how to ensure it fits when it's, ex. 1KB?

Some functions might be stacked, so also their stack sizes.

Anyways, how do I know if the system ram has enough space for it?

Maybe by adding the compiler ram usage report+function stack cost?

Thanks

TDK
July 3, 2021

> Anyways, how do I know if the system ram has enough space for it?

You manually check that the sum of the "max cost" of all IRQs that can be called at once is less than what you have allocated for your max stack size.

The call graph includes overhead for functions called by other functions. For example, Reset_Handler includes stack used by main(), as well as functions that main calls, and so on...

"If you feel a post has answered your question, please click ""Accept as Solution""."
DavidAlfa
DavidAlfaAuthor
Senior II
July 3, 2021

Thanks! Learned something really useful today! Feeling kinda stupid for such basic fault :face_with_tears_of_joy: