Embedded Systems – Drawbacks of Allocating a Huge Amount of Stack for a Single Array

cembedded-systemsmemory usagestack

I usually have no problem deciding whether some data has to be global, static or on the stack (No dynamic allocation here, so no use of the heap). I have also read a few Q/A such as this one but my question is more specific since it involves a huge amount of data, huge compared to the system memory.

I'm working an existing code that I try to improve (design, possible issues, performances, etc.). This code runs on an old 8bit MCU with only 4KB of RAM. In this code I face the use of an array of almost 1KB (yes, 1KB on a 4KB RAM system). Each byte of this array is used, that's not the question. The problem is that this array is a static array in the file where it's declared, so its life cycle is the same as the program one (i.e. can be considered infinite).

However, after reading the code, I just found out that this array has no need of an infinite life cycle, it's built and dealt with in a fully procedural way, so we should be able to declare it only in the function where it's used, this way it would be on the stack, and we would therefore save this 1KB of RAM.

Now the question : Would this be a good idea? From a design point of view, if it doesn't need an infinite/global lifecycle, it belongs to the stack. But hey, that's 1KB out of 4KB, isn't there any drawback of allocating 25% of the RAM like this? (that might be 50% or more of the stack)

Could someone share some experience with this kind of situation, or do someone think about any valid reason not to put this array on the stack? I'm looking for technical drawbacks as well as comments on the design.

The only thing I'm conscious is that I have to make sure I actually have 1KB of stack free when entering this function. Maybe that's all what I have to take care off, maybe not.

Best Answer

The only thing I'm conscious is that I have to make sure I actually have 1KB of stack free when entering this function.

Yes, and that is a strong constraint. You'll better be sure statically than you do have such a large space available on the stack. If the code is small, if you are using a recent GCC to compile your code, see this.

BTW, some cheap microprocessors might make use of a "large" call frame more costly than a "normal" one (e.g. because their instruction set would favor a one-byte offset from the stack pointer). YMMV.

Also, if you are coding in C and if you feel that your large array can have its space reused for other purposes you might consider making it a union member (with a global variable of union type). Yes, that is quite ugly.

Alternatively, you could consider coding some primitive heap allocator suited to your application (and it could have an API different of malloc & free ....).

Related Topic