Why is function size in C always 1 byte?

When we check the size of a function using sizeof() , we always get 1 byte . What does this 1 byte mean?

+84
c function sizeof size
Sep 04
source share
4 answers

This is a violation of the constraint, and your compiler must diagnose it. If he compiles it, despite this, your program has undefined behavior [thanks to @Steve Jessop for the failure mode and see @Michael Burr answer why some compilers allow this]: From C11, 6.5.3.4./1:

The sizeof operator does not apply to an expression that has a function type

+80
04 Sep '12 at 8:00
source share

This is not undefined behavior - C requires diagnostics when using the sizeof operator with a function pointer (function name), since this is a limitation on the sizeof operator.

However, as an extension of the C language, GCC allows arithmetic on void pointers and pointers, which is done by treating the size of a void or function as 1 . As a result, 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 force GCC to issue a warning when using sizeof with these operands using the -pedantic or -Wpointer-arith for GCC. Or make a mistake with -Werror=pointer-arith .

+55
Sep 04
source share

This means that the compiler’s author decided on a value of 1 instead of forcing the daemons to fly out of your nose (indeed, it was another use of sizeof that gave us this expression: β€œThe C compiler MUST issue a diagnostic IF this is the first necessary diagnostic result of your programs, and then MAY cause the demons to fly out of your nose (which, by the way, could be a documented diagnostic message), since it MAY issue further diagnostics for further violations of the law syntax or restrictions (or, for that matter, for any reason, he chooses). https://groups.google.com/forum/?fromgroups=#!msg/comp.std.c/ycpVKxTZkgw/S2hHdTbv4d8J

From this there is the slang term "nasal demons" for what the compiler decides to do in response to the undefined construct. 1 is the nasal daemon of this compiler for this case.

+13
Sep 04 '12 at 8:13
source share

As others have pointed out, sizeof () can take any valid identifier, but does not return the correct (honestly true and valid) result for function names. In addition, it definitely may or may not lead to the "demon nose" syndrome.

If you want to profile the size of your program function, check the linker map, which can be found in the intermediate directory of results (the one where things are compiled into .obj / .o or where the resulting image / executable file is located). Sometimes it is possible to generate or not this map file ... it depends on the compiler / linker.

If you need the size of a function pointer, they have the same size, the size of the address word on your processor.

+7
04 Sep '12 at 8:27
source share



All Articles