Konstantin  Gertsenberger Konstantin Gertsenberger - 1 year ago 71
C++ Question

The size of structure (sizeof) in C++ doesn't correspond the real size in case of arrays

I use dynamic arrays of the following structure:

struct TestStructure
unsigned int serial;
int channel;
int pedestal;
int noise;
int test;

The sizeof(TestStructure) returns 20, so I assume that there is no padding/alignment in the structure. It's logically because there are only 4-bytes types.

But I discovered that size of structure multiplied by element count is not equal the size of the array. There is an additional pad between elements of the array! So, in the following code:

TestStructure* test_struct = new TestStructure[element_count];
for (int i = 0; i < element_count; i++)
FillStructure(test_struct, i, i, i, i, i, i); // assigning 'i' for all elements

Long_t size_value = element_count * sizeof(TestStructure);
unsigned char* p_value = new unsigned char[size_value];
memcpy(p_value, test_struct, size_value);

The output array of chars contains the additional pads between elements:

sizeof(TestStructure) = 20. element_count = 10. size_value = 200. char array in the hex format:
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
6c 6c 2f 6c

1 0 0 0
1 0 0 0
1 0 0 0
1 0 0 0
1 0 0 0
6f 70 74 2f

2 0 0 0

Please, explain me.
Does dynamic array add pads between elements or
Does 'sizeof' operator show wrong size of the structure?

P.S. I use GCC 5.4.0 (Ubuntu 5.4.0-6ubuntu1~16.04.2).

EDIT: I use this code in a macro with ROOT CINT interpreter with GCC compiled library. Sorrry, It seems this bug concerned not with GCC but with ROOT CINT.

Answer Source

Although a compiler can add packing to the end of a struct, a compiler absolutely cannot add additional packing between the elements when manufacturing an array.

For an array TestStructure[n], the address of the i(th) element must be TestStructure + i * sizeof TestStructure. If this were not true then pointer arithmetic would break horribly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download