Home > Mobile >  Stack overflow for huge file with many variables in different scopes
Stack overflow for huge file with many variables in different scopes

Time:05-19

I have a autogenerated file creating structs and doing some calculations with them. Each struct has its dedicated scope.

typedef struct
{
    uint16_t a;
    uint16_t b;
} Addition_t;


uint8_t StructsOverflow(void)
{
    { // use new scope to declare same variable multiple times
        Addition_t x = {.a = 5, .b=6};
        if (x.a == x.b)
            return 1;
    }
    {
        Addition_t x = {.a = 3, .b=6};
        if (x.a == x.b) 
            return 1;
    }
    {
        Addition_t x = {.a = 3, .b=5};
        if (x.a == x.b) 
            return 1;
    }
    // and so on
    // here other structs are created in the same fashion as above
    return 0;
}

For a huge number of Lines (about 100,000 structs), running the .exe stops with a StackOverflow: Exception thrown at 0x00007FF7F2C8B6C8 in EnergyPredictionMain.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x0000001815603000)..

Im using the MSVC 2019 compiler and cppvsdbg for debugging.

Why is there an stackoverflow? In my understanding the variables are destroyed after the scope, so only the memory of one struct should be used.

CodePudding user response:

Why? Because, in a Debug build (IIRC), MSVC doesn't deallocate local variables when they go out of scope in this way. In a Release build, it will probably work.

But what's really broken here, IMO, is whatever it is that autogenerates that file. Would it be practical to change it to generate 100,000 separate sub-functions, each initialising (and then processing) one struct? Then invoke each of them in turn from an (also auto-generated) 'master' function.

If you can do that, it should provide a robust and future-proof fix.

  • Related