Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the correct size of a struct from a pointer without creating an object?

Sorry if the title is confusing. Here's my struct:

struct l_list{
   int number;
   char *name;
   double value;
   struct l_list *next;
};

typedef struct l_list *PhoneBook;

Main function:

int main(void){

   printf("%u\n", sizeof(struct l_list));

   PhoneBook person1;

   printf("%u\n", sizeof(*person1));
   printf("%u\n", sizeof(PhoneBook));

   return 0;
}

The output is:

20
20
4

I understand that PhoneBook is showing 4 bytes because it's only the size of the pointer, but how can you find the size of the actual struct from the typedef PhoneBook?

like image 790
tgun926 Avatar asked Oct 30 '13 02:10

tgun926


1 Answers

You can use the following:

printf("%zu\n", sizeof( *(PhoneBook)NULL ) );

the important question is why is the above valid, aren't you performing indirection on a NULL pointer which would be undefined behavior? No, you are not since sizeof with the exception of variable length arrays is not evaluated at all. If we look at the C99 draft standard section 6.5.3.4 The sizeof operator paragraph 2 says(emphasis mine):

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

furthermore we see the following example in paragraph 5 which confirms this reading:

double *dp = alloc(sizeof *dp);

At compile time the type of the expression with be determined in order to compute the result. We can further demonstrate this with the following example:

int x = 0 ;
printf("%zu\n", sizeof( x++ ));

which won't increment x.

Note: %zu is a platform independent format specifier for the result of sizeof.

like image 109
Shafik Yaghmour Avatar answered Sep 16 '22 22:09

Shafik Yaghmour