C为什么容忍缺少函数声明? [英] Why does C tolerate missing function declarations?

查看:318
本文介绍了C为什么容忍缺少函数声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我们遇到了一个不寻常的现象,一位同事在他的代码中调用了一个通常行为正常的函数,这个函数在libc(gethostbyname)中触发了段错误。令人费解的是,同一个函数在同一运行时在其他源文件中工作没有问题。令人惊讶的是,当使用valgrind时,segfault消失了,事实上,它与valgrind完美协作,没有报告错误。

在安抚编译器神们的许多牺牲之后,我们最终意识到声明函数的头文件从调用该函数的源文件中丢失。为什么gcc / ld不会生成一个错误(甚至是警告),表明函数没有被识别?,为什么gcc / ld不生成错误它是否与valgrind一起工作?



谢谢。 因为你没有使用正确的警告选项,例如 -Wall -Wmissing-prototypes -Wstrict-prototypes 。默认情况下,gcc在接受它时非常自由。
C语言(至少C89)具有隐式函数声明的概念,其中没有原型的函数具有从函数调用中第一次使用派生而来的返回类型和arg列表,并且缺少它,它返回int并且带有一个未指定但固定数量的参数(即不能是可变参数函数)。

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.

解决方案

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

这篇关于C为什么容忍缺少函数声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆