Home > database >  Size of object and C standard
Size of object and C standard

Time:12-23

Looking around I found many places where the way to get the size of a certain object (class or struct) is explained. I read about the padding, about the fact that virtual function table influences the size and that "pure method" object has size of 1 byte. However I could not find whether these are facts about implementation or C standard (at least I was not able to find all them).

In particular I am in the following situation: I'm working with some data which are encoded in some objects. These objects do not hold pointers to other data. They do not inherit from any other class, but they have some methods (non virtual). I have to put these data in a buffer to send them via some socket. Now reading what I mentioned above, I simply copy my objects on the sender buffer, noticing that the data are "serialized" correctly, i.e. each member of the object is copied, and methods do not affect the byte structure.

I would like to know if what I get is just because of the implementation of the compiler or if it is prescribed by the standard.

CodePudding user response:

The memory layouts of classes are not specified in the C standard precisely. Even the memory layout of scalar objects such as integers aren't specified. They are up to the language implementation to decide, and generally depend on the underlying hardware. The standard does specify restrictions that the implementation specific layout must satisfy.

If a type is trivially copyable, then it can be "serialised" by copying its memory into a buffer, and it can be de-it serialised back as you describe. However, such trivial serialisation only works when the process that de-serialises uses the same memory layout. This cannot generally be assumed to be the case since the other process may be running on entirely different hardware and may have been compiled with a different (version of) compiler.

CodePudding user response:

You should use POD (plain-old-data). A structure is POD if it hasn't virtual table, some constructors, private methods and many other things. There is garantee the pod data is placed in memory in declaration order. There is alignment in pod data. And you should specify right alignment (it's your decision). See #pragma pack (push, ???).

  • Related