#include <iostream>
#include <cstdio>
using namespace std;
int main(void)
{
int arr[] = {1,4,2,3,5,6};
int *p = arr;
delete p;
for(int i = 0 ; i < 6; i++)
cout << p[i];
return 0;
}
The output is 142356
.
When I say delete p
why doesn't this delete p?
Shouldn't there be segmentation fault when I run the code?
As a wise old chinese monk once said, 'Undefined behaviour is undefined'.
Seriously, attempting to delete
something that wasn't new
d is undefined.
c and c++ both define the majority of their unexpected functionality as 'undefined'. This means when you have such behaviour you have no idea what will happen. If you're really lucky it will seg fault or similar. More usually, weird and inexplicable things will happen and attempting to reason about them is largely pointless.
The main reason for this is so the implementation of the compiler can be both simpler and also more optimal.
As a C++ programmer, I'd recommend you reading up on Undefined Behaviour, Unspecified Behaviour and Implementation Defined Behavoir. They're all fundamental to understanding how any moderately interesting piece of c++ code will function.
The LLVM project's blog on undefined behavoir is a great read