Search code examples
csegmentation-faultfunction-pointers

Segmentation fault with function pointer


File1.c:

Init()
{
    Add(MyLoop)
}

void MyLoop(bool)
{
    // does stuff
}

File0.c:

int main(void)
{
    Init();
    Run(false);
}

File2.c:

void (* mpfStateMachine)(bool);

void Run(bool Irrelevant)
{
    mpfStateMachine(Irrelevant);
}

void Add(void (* func)(bool))
{
    mpfStateMachine = func;
}

Note: I've ommited the header files, but you may assume the header files (and their #includes) are in order

When I run the above code, it gives me a segmentation fault.

When I comment out "mpfStateMachine(Irrelevant);" inside Run(), it compiles and runs fine.

Any ideas are greatly appreciated.


Solution

  • Turns out the bug was completely unrelated. There was a bug inside MyLoop().

    Thanks to Allan Wind for hinting I should reproduce it myself with a minimal example.