C can be aligned with any other data type?

I implemented a jagged multidimensional array, allocating space for intermediate arrays, as well as the actual elements in 1 large block. While working on this, I decided that just in case I had to take into account the alignment of the stored elements. But I'm not sure if a security check is needed, so I came to ask: will the size of the pointer support alignment for any other type?

In short: given the contiguous memory space from the call to malloc, which looks like this:

| ARRAY OF POINTERS | ALIGN PADDING | ARRAY OF AN ARBITRARY ELEMENT TYPE | 

Do I need padding here when the first array is made of pointers? Are there cases where you need to fill out?

+8
c arrays pointers memory-alignment
source share
2 answers

The C standard does not explicitly guarantee that object pointers have the most stringent alignment requirements. On some systems, a long double may have more stringent alignment requirements; on other systems, function pointers may have more stringent alignment requirements.

However, with a little attention and attention you can define alignment requirements. You need to decide how portable and automatic you need an answer. It is easy to find the answer by compiling the code and finding the answer. It is much more difficult to create a reliable automatic way to do this automatically for any type, not least because an arbitrary type of element can be more or less than an object pointer.

+2
source share

You did not provide all the necessary data necessary to answer this question.

So, here is an example where you need to fill in:

 struct Element { unsigned long long x; ... }; void* ptrArray[TOTAL_SIZE]; 

If you work on the 32-bit platform AND , you have defined an odd number of pointers, then you will need a 4-byte addition to ensure that the 8-byte variable is aligned at the beginning of each element.

Also, note that if you want to store more than one element in an array, the size of the element itself must be a multiple of 8 bytes for this to work.

If you want to abandon the addition altogether, then you will need memcpy use the element from the array and to the array every time you need to access (read or write) this particular element.

+2
source share

All Articles