Hi guys, just playing about with pointers and keywords and to my surprise, this code does not throw up an error... can anyone tell me why?

int main()
{
	int *P = new int;
	*P = 50; 
	cout << *P << endl; // output: 50
	delete P; 
	*P = 4; // Isn't the pointer P now supposed to be dangling?
	cout << *P << endl; // output: 4 (?!) Shouldn't this be an error?	
}

Because today your luck is running good! All kidding aside, it just so happens that that address is still within your address space, so it isn't crashing. Add a few more lines of code and do it and your luck will likely run out! Doing that sort of thing will eventually lead to memory corruption, and believe me, those are the very, very, very worst kinds of problems to encounter. One time I lost three solid weeks due to something like that. What generally happens is that bizarre problems are encountered at some point later in the program due to corruption of your data segmentor something like that.

Edited 6 Years Ago by Frederick2: n/a

Comments
Excellent :)

>Shouldn't this be an error?
It is an error. Just because it doesn't blow up spectacularly when you test doesn't make it any less wrong.

>>// output: 4 (?!) Shouldn't this be an error?
It is. And its a bad one, which went undetected in a sense.

This question has already been answered. Start a new discussion instead.