Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C can pointers be aligned with any other data type?

I've implemented a jagged multi-dimensional array by allocating the space for the intermediate arrays as well as the actual elements in 1 large block. While working on this I figured I had to take into account the alignment of the elements being stored, just in case. But I'm not sure if this safety check is needed, so I've come to ask: Would the size of a pointer keep things aligned for any other type?

In short: Given a contiguous memory space from a call to malloc that looks like:

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

Do I really need the padding here when the first array is made of pointers? Are there cases where the padding is necessary?

like image 252
Brian Rodriguez Avatar asked Dec 31 '14 04:12

Brian Rodriguez


1 Answers

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

However, with a little care and attention, you can determine the alignment requirements. You need to decide how portable and automatic you need the answer to be. It is easy to find an answer by compiling code and finding the answer. It is considerably harder to create a foolproof automatic way of doing it automatically for any type, not least because the arbitrary element type may be larger or smaller than an object pointer.

like image 146
Jonathan Leffler Avatar answered Oct 03 '22 21:10

Jonathan Leffler