Search code examples
cgccsizeofflexible-array-member

Internal mechanism of sizeof in C?


I use sizeof to get size of a struct in C, but the result I got is unexpected.

struct sdshdr {
    int len;
    int free;
    char buf[];
};


int main(){
    printf("struct len:%d\n",(sizeof(struct sdshdr)));
    return 0;
} //struct len:8, with or without buf

my question is why does buf not occupy any space and why is the size of the int type still 4 on a 64-bit CPU?

here is the output from gcc -v:

Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.4.0
Thread model: posix  

Solution

  • The [] is a flexible array member. They do not count towards the total size of the struct, because the C standard explicitly says so:

    6.7.2.1/18

    As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply.

    This is intentional by design, because the purpose of a flexible array member is to allow you to allocate trailing data dynamically after the struct. (When the struct is a file header, protocol header etc.)

    Example including discussion about non-standard gcc extensions and the old pre-C99 "struct hack".