最近在面试的时候碰到了这样一道题,代码如下:
代码如下,求所有打印的结果
#include <vector>
#include <string>
#include <iostream>
using namespace std;
struct Test{
int i;
int *p;
};
int main(int argc, char *argv[])
{
Test t1;
int *p = &t1.i;
p[0] = 1;
p[1] = 5;
cout<<p[0]<<endl; //打印 1
cout<<p[1]<<endl; //打印 5
t1.p = p;
t1.p[0] = 2;
t1.p[1] = 3; //导致出现问题
cout<<t1.p[0]<<endl; //随机值或崩溃
cout<<t1.p[1]<<endl; //随机值或崩溃
return 0;
}
运行会导致程序崩溃,其原理图是这样的:
将结构体t1的p指针指向了自己,而后又修改了t1.p的值,而后又访问t1.p指向的地址的值,可能会崩溃也可能输出随机值。