Main Content

Delete of void pointer

delete operates on a void* pointer pointing to an object

Description

This defect occurs when the delete operator operates on a void* pointer.

Risk

Deleting a void* pointer is undefined according to the C++ Standard.

If the object is of type MyClass and the delete operator operates on a void* pointer pointing to the object, the MyClass destructor is not called.

If the destructor contains cleanup operations such as release of resources or decreasing a counter value, the operations do not take place.

Fix

Cast the void* pointer to the appropriate type. Perform the delete operation on the result of the cast.

For instance, if the void* pointer points to a MyClass object, cast the pointer to MyClass*.

Examples

expand all

#include <iostream>

class MyClass {
public:
    explicit MyClass(int i):m_i(i) {}
    ~MyClass() {
        std::cout << "Delete MyClass(" << m_i << ")" << std::endl;
    }
private:
    int m_i;
};

void my_delete(void* ptr) {
    delete ptr;
}


int main() {
    MyClass* pt = new MyClass(0);
    my_delete(pt);
    return 0;
}

In this example, the function my_delete is designed to perform the delete operation on any type. However, in the function body, the delete operation acts on a void* pointer, ptr. Therefore, when you call my_delete with an argument of type MyClass, the MyClass destructor is not called.

Correction — Cast void* Pointer to MyClass*

One possible solution is to use a function template instead of a function for my_delete.

#include <iostream>

class MyClass {
public:
    explicit MyClass(int i):m_i(i) {}
    ~MyClass() {
        std::cout << "Delete MyClass(" << m_i << ")" << std::endl;
    }
private:
    int m_i;
};


template<typename T> void safe_delete(T*& ptr) {
    delete ptr;
    ptr = NULL;
}


int main() {
    MyClass* pt = new MyClass(0);
    safe_delete(pt);
    return 0;
}

Result Information

Group: Good practice
Language: C++
Default: Off
Command-Line Syntax: DELETE_OF_VOID_PTR
Impact: Low

Version History

Introduced in R2015b