Tiana987642
Tiana987642

Reputation: 754

How to avoid error when access to the deleted memory block?

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

Answers (1)

Kiril Kirov
Kiril Kirov

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

Related Questions