Search code examples
clanguage-lawyerstrict-aliasing

using type punning to decompose object into words


Take a look at the following code which decompose an object into words in order to write the (word-aligned) object to memory using API which accepts only a word:

void func(some_type obj /*obj is word aligned*/, unsigned int size_of_obj_in_words)
{
    union punning{
        unsigned char bytes[4]; /* assume 4 bytes in word in my system */
        uint32_t      word;
    };
    union punning pun;
    unsigned char *legal_aliasing_by_char_pointer;
    for (int i=0; i < size_of_obj_in_words; i++)
    {
        for (int j=0; j<4; j++)
        {
            legal_aliasing_by_char_pointer = (unsigned char *)&obj + j + i*4;
            pun.byte[j] = *legal_aliasing_by_char_pointer;
        }
        /* finally, using word aliasing to decompose object to words */
        /* endianity is not important */
        write_word_to_hw_by_word(pun.word)
    }
}   

I'm trying to perform it in a c standard conforming way, so that strict aliasing rules won't be violated. Is that code achieve that goal?


Solution

  • It looks OK but you can simplify a lot:

    void func(some_type obj)
    {
        uint32_t word;
    
        for (int i=0; i < sizeof obj / sizeof word; i++)
        {
            memcpy(&word, (char *)&obj + i * sizeof word, sizeof word);
            write_word(word);
        }
    }
    

    The alignment of obj doesn't matter. Also you don't need to pass the size since sizeof does the job.

    I suspect it would perform better if you change the function to accept the address of the object, in which case you might want to pass an array length too.