P45 Imminent
P45 Imminent

Reputation: 8591

Is reading a pointer to deleted memory undefined behavior?

Consider

Foo* f = new Foo();
delete f;
Foo* g = f;

Is the final statement now undefined due to my reading a pointer to memory that I don't own? To me it violates the one-past-the-end rule, so it ought to be.

Note that

Foo* f;
Foo* g = f;

is undefined.

Upvotes: 3

Views: 206

Answers (3)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Is the final statement now undefined due to my reading a pointer to memory that I don't own?

No, the statement

Foo* g = f;

will not call undefined behavior per se. The copy operation for a pointer value can be done safely at any time.

But further using the pointer f or g for dereferencing will cause undefined behavior after f was deleted.

You can even use these pointer values safely for e.g. logging purposes:

std::cout << "g = " << g << std::endl;

Note that

Foo* f;
Foo* g = f;

is undefined.

That assumption is wrong. It's neither undefined behavior, again it's dereferencing an uninitialized pointer is undefined behavior, plain assignment is not.

Upvotes: 12

infixed
infixed

Reputation: 1155

It's probably not useful code, but if you think of it as after the delete, f contains a stale pointer. You example copies that stale pointer to g. You are not doing anything really bad until you try to access something with g via the stale pointer.

Upvotes: 1

tadman
tadman

Reputation: 211680

You can copy the pointer, there's nothing preventing you from doing that, but the pointer is to de-allocated memory so it shouldn't be used. If you do use it, you walk right into undefined behaviour, so it's really not a good idea.

Since the f pointer itself is still on the stack, you can copy it without concern. It's just a strange thing to do.

Upvotes: 3

Related Questions