code like:
Code:
int* e = new int;
delete e;
*e = 3; // why no error?
cout << *e << endl; //why no error?
Printable View
code like:
Code:
int* e = new int;
delete e;
*e = 3; // why no error?
cout << *e << endl; //why no error?
The compiler has no way of knowing that e is no longer a valid pointer and so dosen't generate a compiler error. The memory pointed to by e is possibly unchanged because nothing else has used it yet howerver this memory is not marked as allocated and so could be reused at any time which would mean you are overwriting some memory.
After delete you should set the pointer to a NULL pointer to prevent these errors.
This is part of the reason why pointers are called unsafe: they just don't know that they're invalid and might or might not fail. But don't forget one of the many Laws of Computer Science (I think Bjarne Stroustrup first formulated this one): "Undefined behaviour means it works while writing it, works while testing it, and crashes for your most important customer."
I thought it was "blows up". :)
That doesn't work.Quote:
Originally Posted by Quantum1024
Code:x = new int;
*x = 5;
y = x;
delete x;
x = NULL;
*y = 7;
because y conains the original value of x. when you change x to NULL that doesn't change the value of y -- the value of y remains unchanged. y is NOT a pointer to x but a copy of x.
try this -- note the double asterisks, in this example y is a pointer to x, so when you change x you will also change the value to which y points.
Code:x = new int;
*x = 5;
int **y = &x;
delete x;
x = NULL;
**y = 7;
I like that one. :)Quote:
Originally Posted by Ancient Dragon
And "proper feedback"? Well, one of my compilers prints "NULL pointer assignment" but another one lets it pass.
It's about runtime feedback.
Compare:
-> will probably go undetected.Code:int *p = new int;
*p = 5;
delete p;
*p = 6;
-> will crash.Code:int *p = new int;
*p = 5;
delete p;
p = 0;
*p = 6;