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.

commented: Excellent :) +6

>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.

Thanks for the responses guys, much appreciated :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.