Search code examples
c++mallocvalgrindnew-operatordelete-operator

Valgrind claiming I am using malloc when using new


Running Valgrind against an existing codebase, I am getting a lot of "Mismatched free / delete/ delete[]" errors. Many of them are a repeat of one problem: it claims that at line XXX a delete operation is being used, whereas at line YYY a malloc operation is used. However, when I open the file that it complains about and navigate to the line numbers indicated, I find that the memory was not allocated with malloc but with new. The allocated object was an standard ifstream and neither new[] nor delete[] are being used.

I'm running Valgrind 3.5. Does anyone have any idea what is happening? I cannot see how this can be a real error, but I've seen some people claim that Valgrind doesn't turn up many false positives, so I want to have some confidence that this is fake before suppressing it.


Solution

  • You don't provide a sample program, so this is a crystal-ball guess.

    Your program provides an operator new but is missing an operator delete. The following sample program produces the same error message you are seeing:

    #include <new>
    #include <cstdlib>
    
    /*
     * Sample program that provides `operator new`, but not `operator delete`.
     */
    
    // minimal version of new for demonstration purpose only
    void* operator new(size_t numBytes) {
      return malloc(numBytes);
    }
    
    int main () {
      int *p = new int;
      delete p;
    }