Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}   
like image 241
Govind Parmar Avatar asked Dec 07 '25 20:12

Govind Parmar


1 Answers

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.

like image 92
Sergey Kalinichenko Avatar answered Dec 09 '25 09:12

Sergey Kalinichenko