89

当我们使用 来检查函数的大小时sizeof(),我们总是得到1 个字节。这 1 个字节表示什么?

4

4 回答 4

80

这是违反约束的,您的编译器应该诊断它。如果它编译它尽管如此,你的程序有未定义的行为[感谢@Steve Jessop 对故障模式的澄清,请参阅@Michael Burr 的回答,了解为什么一些编译器允许这样做]:来自 C11,6.5.3.4./ 1:

sizeof运算符不应应用于具有函数类型的表达式

于 2012-09-04T08:00:03.270 回答
56

This is not undefined behavior - the C language standard requires a diagnostic when using the sizeof operator with a function designator (a function name) since it's a constraint violation for the sizeof operator.

However, as an extension to the C language, GCC allows arithmetic on void pointers and function pointers, which is done by treating the size of a void or a function as 1. As a consequence, the sizeof operator will evaluate to 1 for void or a function with GCC. See http://gcc.gnu.org/onlinedocs/gcc/Pointer-Arith.html#Pointer-Arith

You can get GCC to issue a warning when using sizeof with these operands by using the -pedantic or -Wpointer-arith options to GCC. Or make it an error with -Werror=pointer-arith.

于 2012-09-04T08:57:16.407 回答
13

它表示编译器编写者决定使用 1 的值,而不是让恶魔从你的鼻子上飞走(事实上,这是另一个未定义的用法,sizeof它给了我们这样的表达:“如果这是第一个需要的,C 编译器本身必须发出诊断由你的程序产生的诊断结果,然后它本身可能会导致恶魔从你的鼻子里飞出来(顺便说一下,这很可能是记录在案的诊断消息),就像它可能会发出进一步的诊断以进一步违反语法规则或约束(或者,就此而言,无论出于何种原因选择)。” https://groups.google.com/forum/?fromgroups=#!msg/comp.std.c/ycpVKxTZkgw/S2hHdTbv4d8J

从这里有一个俚语术语“鼻恶魔”,无论编译器决定做什么来响应未定义的构造。1是这种情况下这个编译器的鼻恶魔。

于 2012-09-04T08:13:57.523 回答
7

正如其他人指出的那样, sizeof() 可以采用任何有效的标识符,但它不会为函数名称返回有效的(真实有效的)结果。此外,它肯定可能会或可能不会导致“鬼出鼻”综合症。

如果您想分析您的程序函数大小,请检查链接器映射,它可以在中间结果目录中找到(东西被编译成 .obj/.o 或生成的图像/可执行文件所在的位置)。有时可以选择生成或不生成此映射文件……它取决于编译器/链接器。

如果您想要指向函数的指针的大小,它们的大小都是相同的,即 CPU 上寻址字的大小。

于 2012-09-04T08:27:45.330 回答