Why does C tolerate missing function declarations?

北战南征 提交于 2019-12-23 18:53:00

问题


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).



来源:https://stackoverflow.com/questions/11687508/why-does-c-tolerate-missing-function-declarations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!