Why does C tolerate missing function declarations?

2019-07-11 09:16发布

问题:

We came across an unusual phenomenon today, a colleague was calling a normally well-behaved function in his code which was triggering a segfault in libc (gethostbyname). The puzzling thing was that the same function worked without trouble in other source files in the same run-time. Astoundingly, the segfault disappeared when valgrind was used, in fact, it worked perfectly with valgrind, with no errors reported.

After much sacrifices to appease the compiler gods we eventually realised that the header file declaring the function was missing from the source file which called the function. Once we added this in, everything ran normally.

Why did gcc/ld not generate an error (or even a warning) indicating that the function was not recognised?, why did it work with valgrind?

Thanks.

回答1:

Because you didn't use the right warning options, such as -Wall -Wmissing-prototypes -Wstrict-prototypes. By default, gcc is quite liberal in what it accepts. The C language (at least C89) has the concept of implicit function declarations, where a function without a prototype has the return type and arg list derived from its first use in a function call, and lacking that, it returns int and takes an unspecified but fixed number of arguments (i.e. can't be a vararg function).