C struct hack at work

后端 未结 4 1436
野趣味
野趣味 2020-11-28 06:39

Is this how one can use the the \"extra\" memory allocated while using the C struct hack?

Questions:

I have a C struct hack implementation below. My questio

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 07:07

    I would advise against that due to possible alignment issues instead consider this:

    struct my_struct
    {
        char *arr_space;
        unsigned int len;
    }
    
    struct my_struct *ptr = malloc(sizeof(struct my_struct) + 10);
    ptr->arr_space = ptr + 1;
    ptr->len = 10;
    

    This will give you locality as well as safety :) and avoid weird alignment issues.

    By alignment issues I meant possible access delays for accessing unaligned memory.

    In the original example if you add a byte or non word aligned member (byte, char, short) then the compiler may extend the size of the structure but as far as your pointer is concerned you are reading the memory directly after the end of the struct (non aligned). This means if you have an array of an aligned type such as int every access will net you a performance hit on CPUs that take hits from reading unaligned memory.

    struct
    {
        byte_size data;
        char *var_len;
        some_align added by compiler;
    }
    

    In the original case you will be reading from the some_align region which is just filler but in my case you will read from aligned extra memory afterwards (which wastes some space but that's typically okay).

    Another benefit of doing this is that it's possible to get more locality from allocations by allocating all the space for variable length members of a struct in one allocation rather than allocating them separately (avoids multiple allocation call overheads and gives you some cache locality rather than bouncing all over memory).

提交回复
热议问题