Search code examples
c++c++17new-operator

C++17 can the 'new' operator still leak memory?


I'm working on a project, and need a char buffer to send a struct over a network. I was using:

char* buf = new char[sizeof(obj)];

Later, someone told me that I would be leaking memory if I did it that way without deleting. I debugged my program with Visual Studio 2017 Professional, and my memory sat constant, no matter how many times I made this buffer.

My question is this: did C++17 fix the memory leak issues that the 'new' operator could cause, or is this something specific to the compiler I'm using? Thanks in advance!


Solution

  • Calling new[] without delete[] will indeed leak memory. You might not see it unless you are leaking lots of buffers, depending on how your app's RTL allocates/caches memory under the hood.

    Traditionally, using a std::vector<char>, or even a std::string, is the preferred choice for dynamic buffers, let them handle their own memory for you, eg:

    std::vector<char> buf(sizeof(obj));
    or
    std::string buf(sizeof(obj), 0);
    

    If you absolutely need new[]/delete[] for some reason, consider using std::unique_ptr<char[]> instead, let it call delete[] for you, eg:

    std::unique_ptr<char[]> buf(new char[sizeof(obj)]);
    or
    auto buf = std::make_unique<char[]>(sizeof(obj));