Search code examples
carraysfunction-pointersinlining

Force the C compiler not to inline an entry from an array


I have an array of C function pointers:

int f1 (void) {
    return 1;
}
int f2 (void) {
    return 2;
}
int (*const functions[])(void) = {f1, f2};

Somewhere else in the code (using a third party tool), I destroy the content of the functions array, before using it. Therefore,

result = functions[0]();

should result in a non definable behaviour (even abortion of the running program). But it does not. The result is as if the destruction has never happened.

Currently, I can imagine two sources of errors for this behaviour:

  1. Destruction does not happen
  2. The compiler inlines the content of the array at compile time and therefore, the destruction has no effect.

So far the 3rd party tool never showed the behaviour of not destructing what it is supposed to destruct. Therefore, I have to assume the latter.

How can I prevent the compiler from inlining the content of the functions array?


Solution

  • The compiler may inline the functions because you declared the array const and it isn't volatile. So according to the abstract execution model, it may suppose that the array never changes.

    To ensure that you may be able to change the array, you'd have to remove the const.

    To ensure that your compiler takes changes from elsewhere into account you'd have to add volatile.