Search code examples
ctype-conversionmemcpy

Is there any situation where this C code would not work as intended?


Is there any possible situation on an x86 or x64 computer where this program would not output 0xFFFF? Or is it guaranteed to work without issues?

#include <stdlib.h>
#include <stdio.h>


int main()
{
    unsigned short int s = 0;
    unsigned long int l = 0xFFFFFFFF;
    memcpy(&s, &l, sizeof(short));
    printf("0x%.4X", s);
    return 0;
}   

Solution

  • Since C does not guarantee the maximum size of a data type, only the minimum one, if you use a compiler with unsigned long taking more than 32 bits where the address of the initial byte corresponds to the most-significant byte of the unsigned long (i.e. the big endian) this would not produce the FFFF result.