Search code examples
c++memory-leaksfunction-pointersstack-overflowunions

C++ - Can union function call make memory leaks


I've had an idea of managing function pointers simular way as .net does and I think thre maybe a memory lick I need conformation of that.

When I call action(5); what happens to 5 in function Test? In my oppinion it stays on stack forever and can result as stackoverflow exception

#include <iostream>
union Action
{
    void (*action)();
    void (*action1)(int);

    void operator()(int i)
    {
        this->action1(i);
    }
    void operator=(void (*action)())
    {
        this->action = action;
    }
    void operator=(void (*action)(int))
    {
        this->action1 = action;
    }
};
void Test()
{
    std::cout << "test";
}
int main()
{
    Action action;
    action = Test;

    action(5);

    char c;
    std::cin >> c;
}

Solution

  • Reading from a union member which is not the last one written to leads to undefined behavior.

    But to answer your question: it depends on the calling convention in use. More specifically, which part of the program is responsible for cleaning up the stack (caller vs. callee). If the caller cleans up the stack, everything should work fine. On the other hand, if the callee has to clean up the stack, the caller has a broken stack frame after the function returns. The next access to a stack-allocated variable will hopefully crash the program -- or even worse, it will only produce erratic behavior which is hard to debug.