Reputation: 754
If the title is not clear, I have this example:
int *a = new int[5];
int*b = a;
delete[] a;
a = NULL;
Now a
is NULL but b
isn't. If I access b
, it will return wrong values and may crash the program.
How to prevent this?
Upvotes: 1
Views: 232
Reputation: 38173
now a is NULL
Not exactly. a
points to some "invalid" (delete
-d) memory. If you want it to be NULL
, annul it manually.
delete a;
must be
delete[] a;
How to prevent this happen?
No way, if you really need to use (raw) pointers - just be careful with the lifetime of a
. It's similar with references - you should just be careful with that, too.
To avoid similar situations, smart pointers are useful. Or just use stack variables instead (where applicable, of course).
Upvotes: 4