Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the sizeof(main), sizeof(printf), sizeof(scanf)?

Tags:

c

sizeof

In the gcc compiler, sizeof(main), sizeof(printf) and sizeof(scanf) all are 1. I want to know how the size of all these are 1. What is the logic behind it?

like image 482
Parikshita Avatar asked Oct 01 '10 11:10

Parikshita


1 Answers

Because the C(99) standard requires (§6.5.3.4/1)

The sizeof operator shall not be applied to an expression that has function type or an incomplete type, to the parenthesized name of such a type, or to an expression that designates a bit-field member.

so the return value is meaningless. If you need the sizeof the function pointer, use

sizeof(&main)
sizeof(&printf)
sizeof(&scanf)

gcc returns 1 on types that the sizeof is meaningless (see c-common.c):

4187     if (type_code == FUNCTION_TYPE)
4188       {
4189         if (is_sizeof)
4190           {
4191             if (complain && (pedantic || warn_pointer_arith))
4192               pedwarn (loc, pedantic ? OPT_pedantic : OPT_Wpointer_arith,
4193                        "invalid application of %<sizeof%> to a function type");
4194             else if (!complain)
4195               return error_mark_node;
4196             value = size_one_node;
4197           }
4198         else
4199           value = size_int (FUNCTION_BOUNDARY / BITS_PER_UNIT);
4200       }
4201     else if (type_code == VOID_TYPE || type_code == ERROR_MARK)
4202       {
4203         if (type_code == VOID_TYPE
4204             && complain && (pedantic || warn_pointer_arith))
4205           pedwarn (loc, pedantic ? OPT_pedantic : OPT_Wpointer_arith,
4206                    "invalid application of %qs to a void type", op_name);
4207         else if (!complain)
4208           return error_mark_node;
4209         value = size_one_node;
4210       } 
like image 59
kennytm Avatar answered Nov 08 '22 14:11

kennytm