Why does calling external function pointer crash the program?

Viewed 312

There are two source files, a.c and b.c. a.c:

int main(void)
{
    foo();
    return 0;
}

b.c:

#include <stdio.h>

static void bar(void)
{
    puts("Hola!");
}

extern void (*foo)(void) = bar;

Compile them together (cl a.c b.c), run the program, the program will crash. Why is that?

However, a declaration like extern void (*foo)(void); would solve the problem.

My environment is Windows MSVC:

Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8804 for 80x86
Copyright (C) Microsoft Corp 1984-1998. All rights reserved.

I guess it's because:

  1. Since foo is not declared, the compiler guesses that it's a function.
  2. However, foo is not a function, but a variable, so the calling fails.
1 Answers

Since foo is not declared, the compiler guesses that it's a function. However, foo is not a function, but a variable, so the calling fails.

Before C99 (request for a check), C does not force the user to declare functions before calling them, so there are no warnings or errors from the compiler; What's more, there is really one foo defined, no matter it is a variable or a function, so there are no warnings or errors from the linker. These make this issue hard to find.

However, as found in this SO post, sometimes an implicit function call like this would become a undefined behaviour (UB):

J.2 Undefined behavior

— For call to a function without a function prototype in scope where the function is defined with a function prototype, either the prototype ends with an ellipsis or the types of the arguments after promotion are not compatible with the types of the parameters (6.5.2.2).

Related