Search code examples
cpointersstructpacking

Is it safe to make assumptions about the packing of two consectutive pointers in a C struct?


I'm working on language bindings from GObject based libraries to Standard ML. More precisely I'm implementing support for the G(S)List collection type. This implementation requires extracting data from G(S)Lists links and getting the next link from within Standard ML. Rather that calling one of the G(S)List functions through the FFI, I was hoping that it would be possible to use the FFI's pointer manipulation functions to access the appropriate struct elements for efficiency. However, this requires that it's possible to predict the offset of the second, next link, pointer in the struct. For reference, this is what the GSList link struct looks like

struct GSList {
    gpointer data;
    GSList *next;
};

which I think is no surprise to anyone. It's safe to assume that the pointer to a struct points to it's first element, ie the data pointer, but how about the second element? Can I make any platform independent assumptions about the offset of the second element in relation to the first?


Solution

  • It's safe to assume that the pointer to a struct points to it's first element, ie the data pointer, but how about the second element?

    Yes. This is safe. The address of a struct object and the address of its first element are guaranteed to be the same. No padding is allowed before the first member of a struct.

    Can I make any platform independent assumptions about the offset of the second element in relation to the first?

    No. This is not safe. There may be padding bytes between first and second element of the structure and any assumptions is non-portable. But you can use offsetof to get the offset of any member from the start of the structure.

    For example, you can the offset of next with:

    size_t next_offset =  offsetof(struct GSList, next);
    

    GCC provides an attribute to disable the padding:

    __attribute__((packed))
    

    And similar option is provided by MSVC too.