程序运行在X86和X64机器上由字节分配不一样引发的问题



#include "stdafx.h"
#include "iostream"
using namespace std;


struct S
{
int i = 10;
int *p = (int*)1111;
};//size of it is 16.
int main()
{
S s;
int *p = &s.i;
cout <<"size of s:"<< sizeof(s) << endl;
cout << "size of p[0]:"< cout<<"sizeof p:"< cout << sizeof(s.p[0]) << endl;
p[0] = 4;
p[1] = 3;
s.p = p;
s.p[1] = 1;
s.p[0] = 2;
    return 0;
}
    这样一段代码,在X64上正常运行,但是在X86机器上就会出错。经过我的分析,问题就出在最后两行代码。
首先,明确一个问题:sizeof(s)在X64中是16B,X86中是8B。x86下,int是四个字节,由此p[0]指向了指针s.i,而p[1]指向了s.p。赋值s.p = p,相当于把s.p指向了s;s.p[1]=1把s.p修改为了1,把p[1]修改为了1,也把s.p指向了0x0001的位置。执行s.p[0] = 2,就是修改0x0001位置的内容了,当然出现错误。
  如果是X64下,p[0]=s.i; p[1]填充;p[2]和p[3]组成了指针s.p。 因此最后修改s.[p]的时候修改分别指向了1,2位置,不过没有发生乱引用,所以没报错。

你可能感兴趣的:(C/C++,x86,x64,C++)