Having nothing else to do, I decided to write a simple C program that checked the amount of bytes in certain variables, without using sizeof.
This code works and displays the correct values on both my mac and linux box:
Code:
#define count(x,y) for(x=1; x; x <<= 1) y++
void verify_bits_count() {
char chr_init = 0;
short sht_init = 0;
int int_init = 0;
long lng_init = 0;
short chr_ret = 0, sht_ret = 0, int_ret = 0, lng_ret = 0;
count(chr_init, chr_ret);
count(sht_init, sht_ret);
count(int_init, int_ret);
count(lng_init, lng_ret);
printf("\n\nbit count\n\n");
printf("char has %d bytes\n",chr_ret/8);
printf("short has %d bytes\n",sht_ret/8);
printf("int has %d bytes\n",int_ret/8);
printf("long has %d bytes\n",lng_ret/8);
}
However, this code only works on my mac (which afaik has the same architecture as my linux):
Code:
short loop_test(char *chr_char) {
short chr_val = 0;
int chr_ret = 0;
for (chr_val = 0; chr_val <= 100; chr_val++)
chr_ret += (chr_char[chr_val] == -1 ? 1 : 0);
return chr_ret;
}
#define loop_tst(cc,cv,cr) for (cv = 0; cv <= 100; cv++) cr += (cc[cv] == -1 ? 1 : 0);
void verify_bits_loop() {
char *dst = malloc(100);
short chr_ret = 0;
short sht_ret = 0;
short int_ret = 0;
short lng_ret = 0;
char chr_val = 0xFFFFFFFFFFFFFFFF;
memset(dst, 0x00, 100);
strcpy(dst, (char *)&chr_val);
loop_tst(dst,chr_val,chr_ret);
short sht_val = 0xFFFFFFFFFFFFFFFF;
memset(dst, 0x00, 100);
strcpy(dst, (char *)&sht_val);
loop_tst(dst,sht_val,sht_ret);
int int_val = (int)0xFFFFFFFFFFFFFFFF;
memset(dst, 0x00, 100);
strcpy(dst, (char *)&int_val);
loop_tst(dst,int_val,int_ret);
long lng_val = 0xFFFFFFFFFFFFFFFF;
memset(dst, 0x00, 100);
strcpy(dst, (char *)&lng_val);
loop_tst(dst, lng_val, lng_ret);
printf("\n\nloop test\n\n");
printf("char has %d bytes\n",chr_ret);
printf("short has %d bytes\n",sht_ret);
printf("int has %d bytes\n",int_ret);
printf("long has %d bytes\n",lng_ret);
}
The difference is in the "char", where the mac correctly displays it as 1 byte, whereas the linux interprets it as two in the last function. Any ideas why it does that?