Fihop
Fihop

Reputation: 3177

Delete void* pointer in c++

I'm reading thinking in c++, chapter 13: dynamic object creation. In this chapter, Eckel talk about deleting void* may be probably a bug. The following paragraph confuses me.

The other memory leak issue has to do with making sure that delete is actually called for each object pointer held in the container. The container cannot "own" the pointer because it holds it as a void* and thus cannot perform the proper cleanup. The user must be responsible for cleaning up the objects. This produces a serious problem if you add pointers to objects created on the stack and objects created on the heap to the same container because a delete-expression is unsafe for a pointer that hasn't been allocated on the heap.

Can anyone explains more detail why "adding pointers to objects created on the stack and objects created on the heap to the same container" produces a serious problem?

To make the problem more clearly, I add the related code snippet.

class Stack {
  struct Link {
    void* data;
    Link* next;
    void initialize(void* dat, Link* nxt);
  }* head;
public:
  void initialize();
  void push(void* dat);
  void* peek();
  void* pop();
  void cleanup();
};

Upvotes: 1

Views: 2797

Answers (2)

SomeWittyUsername
SomeWittyUsername

Reputation: 18348

This paragraph is indeed a bit vague. It mixes 2 different issues and that leads to confusion, in my opinion.

  1. In order to correctly delete an object, its type must be known to the compiler. For void* the type isn't known (that's exactly the point of using void* - to hide the actual type). So the deletion can't be performed on such object without casting to the proper actual type.
  2. Normally usage of void* implies that ownership of the pointed object belongs to some outer entity by design, and not to the entity containing the pointer. Inside the entity the pointer is opaque and serves as a handler to an external object, which is a black-box as far as the the entity is concerned. The Stack class must be well aware of the responsibilities division and must not attempt to destroy the void* object since it has no idea neither about it's lifetime (leading to attempt to free stack variable, for example), nor about the operations that should be done upon the destruction (leading to functional incorrectness).

Upvotes: 1

Mppl
Mppl

Reputation: 961

As a general rule objects on the stack dont need to be Deleted, objects on the heap need. If you place them in the same container how do you keep track of which ones to delete? You better have two containers, one for objects on the stack(the ones that dont need delete), other for objects on the heap(the ones that need to be deleted).

Upvotes: 2

Related Questions