0

Hi,
Does anyone know anything about stack size reduction? I`ve gone thru the C forum and I did not find anything. Wat r the standard techniques to reduce the stack size?
From wat I`ve heard, one of the best ways is to try and avoid static arrays in functions.
Is there anything else?

Thanks.

2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by Salem
1

Why do you care?
Today's desktop PCs use virtual memory for allocating stack space, and the default initial size is usually around the 1MB mark. In windows for example, the stack is allocated on demand in 4K blocks at a time. Saving a few bytes here and there isn't going to matter.

Places where you might care.
- DOS (real DOS, not win32 console which many mistake for DOS), which has an upper limit of 64K for stack size.
- embedded systems or smaller micro processors which can have very small stacks, say a couple of hundred bytes.

> From wat I`ve heard, one of the best ways is to try and avoid static arrays in functions.
Which is exactly the wrong thing, because making arrays static takes them off the stack.

> Is there anything else?
In addition to the making large arrays static, you can add
- avoid recursion
- pass structs by reference (a const pointer), not by value
- group same sized variables together (for structs and for locals)
Eg.

int a;
short b;
int c;
char d;

may take up more space than this, due to all the internal padding and alignment.

int a;
int c;
short b;
char d;

- if you're passing the same group of variables (say x,y,z coordinates), then consider making a struct out of them, and see above.
- declare variables in the narrowest scope possible.

int a, b;
if ( foo ) {
  // stuff with a
} else {
  // stuff with b
}

may take up more space than this, since the compiler may see that a and b can never co-exist, and thus could share the same memory location.

if ( foo ) {
  int a;
  // stuff with a
} else {
  int b;
  // stuff with b
 }

Do you want to trade stack size for poor performance?
- use malloc/free to allocate any remaining large struct / array which you can't make static.

Do you want to trade stack size for poor program style?
- turn frequently passed parameters into global variables.

Votes + Comments
Damn good answer.
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.