Stack usage on function call


I am encountering a stack usage problem : if a function (or Statement expression  or Lambda) returning a structure is called directly as a argument of another function, a new structure is added on the stack and memory is not reused.

The example code below adds 4 structure to the stack


struct TestStruct
    uint32_t field1;
    uint32_t field2;
    uint32_t field3;
    uint32_t field4;
} ;

struct TestStruct initStructure(uint32_t f1, uint32_t f2, uint32_t f3, uint32_t f4)
    TestStruct myStruct;
    struct.field1 = f1;
    struct.field2 = f2;
    struct.field3 = f3;
    struct.field4 = f4;
    return myStruct;

void doStuff(struct TestStruct myStruct)
    printf("f1 = %d, f2 = %d, f3 = %d, f4 = %d", myStruct.field1, myStruct.field2, myStruct.field3, myStruct.field4);

int main(void)


I would have thought that as the structure would behave like automatic variables in separate scopes, and memory would have been reused. Adding scopes around each function call does nothing, so the structure are reserved on the stack when you enter the main function.

This happens with -fstack-reuse=all and -Os, -Og, -O1, -O2. is there a way to force stack reuse on this variables ?


More questions in this forum