Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zero size struct

Tags:

c++

c

gcc

I noticed that when compiled with GCC 4.6 sizeof(Foo) is 0 and sizeof(Bar) is 1. For some reason adding an empty array into an empty structure made its size 0. I thought that the sizes of both structures must be the same. What is going on here?

struct Foo
{
    char x[];
};

struct Bar {};
like image 784
pic11 Avatar asked Jun 10 '12 19:06

pic11


1 Answers

Neither struct declaration is allowed by the C standard. 6.7.2.1 (8) in n1570:

If the struct-declaration-list does not contain any named members, either directly or via an anonymous structure or anonymous union, the behavior is undefined.

And paragraph 18 in the same section:

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.

(emphasis mine)

Flexible array members are not allowed in C++, so the code is not valid C++ either.

As it is not valid code, the values reported by sizeof for these are meaningless.

like image 55
Daniel Fischer Avatar answered Nov 15 '22 18:11

Daniel Fischer