Electronic – How does the Array allocated in the stack

cmemorystack

I was testing the code below on my STM32 board, but I could't understand how the array was being allocated in the stack.

I'm assuming that there are 200 bytes of memory in STM32.

Here is the code:

void test1()
{
  char data[1000]={0};
}

void test2()
{
  char data[1000];
  data[999] = 50;
  lcdAdjustBacklight(data[999]);//just adjust back light
}

So, when I add test1() into my main() function, the program will crash when run on the MCU. Obviously, the stack is overflow. However, when I add test2() into main(), the MCU processes the program just fine. I wonder how the stack allocation works for an uninitialized array.


Edit: I finally figured it out. I checked the assembly code, in test1 the compiler allocated the memory, indeed. But in test2, the compiler optimized the array, so it does not allocated memory for it.

Best Answer

Note that 'MCU will stop running' versus 'MCU still running' is not a good criterium for 'everything is OK'.

On ARM chips. the stack grows down (starts high, each nested stack frame occupies lower addresses), in most cases starting from the highest RAM address. When the stack grows too large for the available stack space, it will overwrite the heap, and after that global data. Whether this is harmful for the program depends. On what? That's mighty complex to figure out.

Note that the 'data[999]' in your 'char data[1000]' is the highest address within this variable, so it is the least likely to cause a problem. using data[0] (which is at the lowest address) is more likely to cause a problem.

Again on ARM, a function that does not call deeper functions might not use the stack at all (the return address is saved in a register, not on the stack).

So in all probability, both your programs are bad, but whether in practice that translates to 'seems to work' or 'seems to stop' is very difficult to predict.