1

This segment calls func3 with argument *p and since p being a null pointer this program should have crashed at function call.

#include <iostream>

using namespace std;

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


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

I thought compiler is not resolving *p in case of pass by reference, just making an alias to it, somehow. So, I tried the following code segment:

#include <iostream>

using namespace std;

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


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

In func3(&(*p)), I'm de-referencing a null pointer and then referencing it again. But it still won't crash.

Vishaal Shankar
  • 1,648
  • 14
  • 26
  • 3
    "since p being a null pointer this program should have crashed" no, it may crash but does not have to. – Slava Feb 22 '18 at 04:27
  • Keep in mind since you're not doing anything with it after dereferencing the null pointer, your compiler's optimizer may have decided this code is not needed and essentially skipped it. To work around this try reading, writing, and/or printing out the value of the dereferenced null pointer. – MrEricSir Feb 22 '18 at 04:48
  • My Little Optimizer: Undefined Behavior is Magic! https://www.youtube.com/watch?v=g7entxbQOCc – Jeremy Friesner Feb 22 '18 at 05:22

1 Answers1

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.

Niall
  • 30,036
  • 10
  • 99
  • 142
  • 1
    Just leaving this here for more info. Isssues in c++: http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#232 "We agreed that the approach in the standard seems okay: p = 0; *p; is not inherently an error. An lvalue-to-rvalue conversion would give it undefined behavior." – Sumit Dhingra Mar 18 '18 at 07:27