While learning c I have implemented my own memcpy functions. I have used a wider type( uint32_t
) in the function. (For simplicity the function is restricted to types that are multiples of 4 and the data is properly aligned )
void memcpy4( void* dst , void* src , int size )
{
size /= 4;
for ( int i = 0 ; i < size ; i++ )
((uint32_t*)dst)[i] = ((uint32_t*)src)[i];
}
I did some reading on type punning and strict aliasing and I believe the function above breaks the rule. The correct implementation would be this since you can use a char:
void memcpy4( void* dst , void* src , int size )
{
for ( int i = 0 ; i < size ; i++ )
((char *)dst)[i] = ((char *)src)[i];
}
I tried to do some casting trough an union, but that turned out to be invalid as well.
How could such function be implemented with a wider type and not break the strict aliasing rule?