为什么这个程序没有崩溃?

时间:2018-02-22 04:25:31

标签: c++ pointers

此段使用参数*p调用func3,并且由于p是空指针,因此该程序应该在函数调用时崩溃。

#include <iostream>

using namespace std;

void func3(int &a)
{
 cout<<"Not Crashing?\n";
}


int main()
{
  int *p = NULL;
  func3(*p); 
  return 0;
}

我认为编译器在通过引用传递时不会解析*p,只是以某种方式为它创建别名。所以,我尝试了以下代码段:

#include <iostream>

using namespace std;

void func3(int *a)
{
 cout<<"Not Crashing?\n";
}


int main()
{
  int *p = NULL;
  func3(&(*p));  // &(*p) == p
  return 0;
}

func3(&(*p))中,我取消引用空指针,然后再次引用它。但它仍然不会崩溃。

1 个答案:

答案 0 :(得分:2)

The obligatory note is that any attempt to use the de referenced value is undefined behaviour, it is not required to crash.

In general it would crash, if you attempted to write (or read) from the dereferenced pointer. But you don’t, so the access violation you are expecting never happens.