# V772. Calling the 'delete' operator for a void pointer will cause undefined behavior.

The analyzer detected a possible error that has to do with using the 'operator delete' or 'operator delete[]' together with a non-typed pointer (void*). As specified by the C++ standard (subclause $7.6.2.8/3), such use of 'delete' results in undefined behavior.

Consider the following example:

    class Example
    {
      int *buf;

    public:
      Example(size_t n = 1024) { buf = new int[n]; }
      ~Example() { delete[] buf; }
    };

    ....
    void *ptr = new Example();
    ....
    delete ptr;
    ....

What is dangerous about this code is that the compiler does not actually know the type of the 'ptr' pointer. Therefore, deleting a non-typed pointer may cause various defects, for example, a memory leak, as the 'delete' operator will not call the destructor for the object of type 'Example' pointed to by 'ptr'.

If you really mean to use a non-typed pointer, then you need to cast it to the original type before using 'delete' ('delete[]'), for example:

    ....
    void *ptr = new Example();
    ....
    delete (Example*)ptr;
    ....

Otherwise, it is recommended that you use only typed pointers with 'delete' ('delete[]') to avoid errors:

    ....
    Example *ptr = new Example();
    ....
    delete ptr;
    ....

This diagnostic is classified as:

CWE-758 CERT-MSC15-C

You can look at examples of errors detected by the V772 diagnostic.