This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Stack pointer gets corrupted

At the beginning of main I have two variables, namely:

unsigned char audioDataBuffer1[512];
unsigned char audioDataBuffer2[512];

Later in the code I use them as buffers for audio data from SD Card.

The problem is that the stack pointer is set too low and these big variables overwrite my stack pointer which is set automatically by Keil startup code. How is this possible?

I have noticed that the problem disappears when I set above variables to global, or when I use malloc instead.

I would appreciate if you could explain what goes wrong here and is there any reason I should not declare large variables like this?

Thank you.

Parents
  • A local function can have variables of limited size. For best utilization of stack we should avoid structures and arrays of larger size defining in the local function. Instead declare them as global variables. I have faced a similar issue , I have declared an array of 2000 Bytes for a local variable in a function. When i call that function these bytes gets corrupted at some point. Later i have made the array as global and everything works fine. I have found in some text that arrays and structures of more length should not be declared as local variables.

Reply
  • A local function can have variables of limited size. For best utilization of stack we should avoid structures and arrays of larger size defining in the local function. Instead declare them as global variables. I have faced a similar issue , I have declared an array of 2000 Bytes for a local variable in a function. When i call that function these bytes gets corrupted at some point. Later i have made the array as global and everything works fine. I have found in some text that arrays and structures of more length should not be declared as local variables.

Children
No data