Search code examples
c++visual-studiomemory-leak-detectorcrtdbg.h

It seems like I cannot use MS leak detector for the new expression `new (std::nothrow)`. Is that correct?


I'm trying to get the file and the line where the leak is occurring with the new expression new (std::nothrow).

The commented new expression in the code below does not compile.

#include <iostream>

int main()
{
    #ifdef _DEBUG
    int* p = new (_NORMAL_BLOCK, __FILE__, __LINE__) int(10);
//  int* q = new (std::nothrow, _NORMAL_BLOCK, __FILE__, __LINE__) int(10); 
    #else
    int* p = new int(10);
    int* q = new int(10);
    #endif

    _CrtDumpMemoryLeaks();
}

I'm also curious to know where does <iostream> includes <crtdbg.h>. I just couldn't find it. But of course, it must be there, somewhere.


Solution

  • Not directly. Microsoft doesn't provide an void* operator new(std::nothrow_t, const char* file, int line) but you can trivially do so yourself. Just forward to the throwing version and in the catch handler return NULL;.