分段错误(核心转储)和指针声明的位置



以下代码在g++编译器中正常运行:

int ti = 72;
int *pooh = &ti;
std::cout<<*pooh; 
int i,*p,*q,*r;
int &j = i;       
i  = 36;
p  = &i;         
*q = i;          

std::cout<<"i: ( "<<i<<" , "<<&i<<" ) "<<std::endl;
std::cout<<"j: ( "<<j<<" , "<<&j<<" ) "<<std::endl;
std::cout<<"p: ( "<<*p<<" , "<<p<<" ) "<<std::endl;
std::cout<<"q: ( "<<*q<<" , "<<q<<" ) "<<std::endl<<std::endl;
j = 107;
std::cout<<"i: ( "<<i<<" , "<<&i<<" ) "<<std::endl;
std::cout<<"j: ( "<<j<<" , "<<&j<<" ) "<<std::endl;
std::cout<<"p: ( "<<*p<<" , "<<p<<" ) "<<std::endl;
std::cout<<"q: ( "<<*q<<" , "<<q<<" ) "<<std::endl;

但是改变ti指针声明的位置会导致分段错误(核心转储(:

int i,*p,*q,*r;
int &j = i;       //shallow copy , referencing , j is an alias of i
i  = 36;
p  = &i;          //shallow copy , referencing , p is an alias of i
*q = i;           //deep copy  , value copied after deferencing stored in seperated memory in stack
int ti = 72;
int *pooh = &ti;
std::cout<<*pooh; 
std::cout<<"i: ( "<<i<<" , "<<&i<<" ) "<<std::endl;
std::cout<<"j: ( "<<j<<" , "<<&j<<" ) "<<std::endl;
std::cout<<"p: ( "<<*p<<" , "<<p<<" ) "<<std::endl;
std::cout<<"q: ( "<<*q<<" , "<<q<<" ) "<<std::endl<<std::endl;
j = 107;
std::cout<<"i: ( "<<i<<" , "<<&i<<" ) "<<std::endl;
std::cout<<"j: ( "<<j<<" , "<<&j<<" ) "<<std::endl;
std::cout<<"p: ( "<<*p<<" , "<<p<<" ) "<<std::endl;
std::cout<<"q: ( "<<*q<<" , "<<q<<" ) "<<std::endl;

有人能解释一下原因吗?

你第一次很幸运。两个版本都取消引用未初始化的指针q。根据q的随机值,程序将崩溃或执行未定义的操作。

最新更新