Is there a way for force gcc to free the space from the stack when variables go out of scope

234 Views Asked by At

I have the following piece of code:

extern void func1(char *array);
extern void func2(char *array);

void myfunction(void) {
    if (somecondition) {
        char var2[256];
        func2(var2);
    }
    if (someothercondition) {
    {
        char var3[3];
        func3(var3);
    }
}

I cannot get my compiler (gcc) to call func3 with only 3 bytes used for var3 in the stack. It always allocates the space for the var2 used in the scope for func2 call, even though this variable is out of scope and could have been safely removed from the stack.

I have tried several options that I found in the gcc documentation:

  • fomit-frame-pointer
  • fconserve-stack

I have tried this on both x86 and ARM architectures and it behaves identically.

The rationale behind this question is to use only the stack size that is necessary.

And the related question: if it is possible to optimize the stack space, is it possible to add the stack used for each sub-function call in the .su file generated by the option -fstack-usage .

thanks

1

There are 1 best solutions below

1
anton-tchekov On

You could do something like this:

extern void func1(char *array);
extern void func2(char *array);

void _helper(/* neccessary parameters */)
{
    char var2[256];
    func2(var2);
}

void myfunction(void) {
    if (somecondition) {
        _helper(/* neccessary parameters */);
    }
    if (someothercondition) {
    {
        char var3[3];
        func3(var3);
    }
}

Because the allocation happens in a different function the compiler will only allocate the memory when the _helper is called. This is probably susceptible to optimization (inlining), but moving the helper to a different compilation unit (new c file) will prevent that.

Of course this will come at a cost of a function call and parameter copying.

Anyways, if the stack space problem is related to recursion, you should consider replacing that with an iterative solution that uses explicitly pre-allocated stack.