1

I test a program below:

#include <stdio.h>
#include <stdlib.h>

typedef struct _node_t {
    int id;
    int contents[0];
}node_t;

int
main(int argc, char* argv[])
{
    printf("sizeof node_t is: %d\n", sizeof (struct _node_t)); // output: 4

    node_t *node = (node_t*)malloc(sizeof(node_t) + sizeof(int) * 3);

    printf("sizeof node is: %d\n", sizeof (node)); // output: 8

    return 0;
}

And the size of node instant is 8. However, in the malloc function, I put extra 3 integers to the node structure. Why the output of node size is still 8?

PS: gcc (GCC) 4.6.3 20120306 (Red Hat 4.6.3-2)

injoy
  • 3,993
  • 10
  • 40
  • 69
  • possible duplicate of [What happens if I define a 0-size array in C/C++?](http://stackoverflow.com/questions/9722632/what-happens-if-i-define-a-0-size-array-in-c-c) – Lundin Sep 18 '12 at 10:59

2 Answers2

7

Because sizeof() is a compiletime "operator" that returns the size of the type. It doesn't know or even care what you malloc()ed.

EDIT: besides, you're taking the size of a pointer in your second try :-) You probably meant to use something like "sizeof(*node)" there, which would have given you "4" again.

EDIT 2: this is also the reason why you can do something like sizeof(*Pointer) or sizeof(Pointer->Element) even if 'Pointer' has never been initialized or is otherwise invalid. sizeof() doesn't care a thing about the content of anything, it merely looks at the resulting type of the expression.

Christian Stieber
  • 9,954
  • 24
  • 23
3

First: do not cast the return value of malloc() in C.

Second: it's better to not repeat the type name, but instead use the left-hand pointer you're assigning the malloc():ed pointer to, since it already has the type. Thus:

node_t *node = malloc(sizeof *node + 3 * sizeof(int));

In this code, the evaluation of the sizeof operator expressions are done at compile-time, and thus there's no information available from the execution of the code.

Since C99, it's possible to get a partial-runtime evaluation of sizeof, see this Wikipedia text. The most basic example given is:

size_t flexsize(int n)
{
   char b[n+3];      /* Variable length array */
   return sizeof b;  /* Execution time sizeof */
}

The above requires runtime evaluation of sizeof, since the exact value of n is not constant and not known at compile-time. The above would not compile in pre-C99 versions of C.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606