-1

Why the following C++ code does not give a segmentation fault, I am trying to access something that I have deleted.

#include <iostream>
using namespace std;
void fun ( int * ptr )
{
    delete ptr;
}
int main ()
{
    int * ptr = new int ;
    *ptr = 6;
    fun ( ptr );
    cout<<*ptr;
    return 0;
 }

1 Answers1

1

Accessing something you've deleted doesn't automatically result in segfault.

The behavior is undefined. It might segfault, it might not. You can never know.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • How can you guarantee that it will not cause segfault ? – Tharif Mar 22 '15 at 07:47
  • @utility Because the C++ standard defines it to be *undefined behavior*. It doesn't say it should cause a segfault. Segfault only happens if the OS is not happy with you trying to access the memory address. – Emil Laine Mar 22 '15 at 07:57