p*****e 发帖数: 537 | 1 我想从integer bit-to-bit的cast到double:
int x = 0;
double f = *((double*)&x);
这个cast为啥一直是有效的?一个integer的地址是4-byte aligned,也就是说,valid
integer address should end with 0, 4, 8 or c. double是8-byte aligned, 也就
是,valid double address should end with 0 or 8.
那么如果x的地址是 end with 4 or c, 这个cast为啥还是有效的?
为了保证这个问题始终出现,我把程序改成:
int x[2] = {0, 0};
double f1 = *((double*)&x[0]);
double f2 = *((double*)&x[1]);
这样做保证x[0]和x[1]里始终有一个的地址不是 8-byte aligned,但最后的结果是f1
是0,f2是乱码,但都没报错。
这种cast为啥可以不考虑alignment?是compiler动了什么手脚吗? | s**x 发帖数: 7506 | 2 1) I do not think the alignment is enforced, you can always cast at any
address. the alignment may be true for some other machines, but not the
normal pc we work with.
2) as long as I understand, the alignment is just more efficient,
that is why you see alignment is data structures, malloc return values etc.
3) C is very flexible, you can cast any number to an address and do
something, I guess hackers like that a lot.
you have to know what you are doing. |
|