c空指针一定会让程序crash非也非

废话不多说,直接看题:

#includeiostream

#includecstdlib

#includevector

#includestring.h

#includestdio.h

usingnamespacestd;

classCDemo{

public:

CDemo()

{

coutconstructinvoke!endl;

};

voidshow(void){

printf(showcalled\n);

}

};

intmain(){

CDemo*d=NULL;

printf(\n);

d-show();

printf(\n);

return0;

}

面试官:上面这段代码能运行吗,为什么?

面试者:不行,会直接crash。因为访问了空指针。

面试官:谢谢,您可以回家了!

面试者:什么情况?

我们直接上运行结果,如下:

可以看到,程序安稳的运行了!要解释这个问题,需要从编译器的角度来解释它:

classCDemo{

public:

inta;

CDemo()

{

coutconstructinvoke!endl;

};

voidshow(void){

printf(showcalled\n);

}

};

intmain(){

CDemo*d=NULL;

d-show();

return0;

}

对于c++编译器来讲,会将上面的代码编译为,如下:

structCDemo{

inta;

};

voidCDemo_show_void(structCDemo*c,void){

printf(showcalled\n);

}

intmain(){

CDemo*d=NULL;

CDemo_show_voidshow(d);

return0;

}

好了,今天分享就到这!感谢阅读!




转载请注明:http://www.aierlanlan.com/rzdk/4849.html

  • 上一篇文章:
  •   
  • 下一篇文章: 没有了