Question

I am using HDF5 to read a string into a char* allocated by new[]. I then use a string::assign() call to copy this data to where I actually want it. I then call delete[] on that char*. This is showing up as the source of a memory leak using totalview. It shows mangled calls in stdlibc++ under delete[] to replace_safe, mutate, create, then malloc. What is going on, and is this really a memory leak? I have set GLIBCXX_FORCE_NEW=1 here as well.

Here is example code that duplicates the situation. Note that valgrind shows no leaks and if I don't put a breakpoint before the cout call, there is no leak found by totalview.

#include <string>
#include <iostream>
#include <cstdlib>

int main()
{
    std::string str;

    int len = strlen(getenv("PATH"));
    char* x = new char[len + 1];
    strcpy(x, getenv("PATH"));
    x[len] = '\0';

    str.assign(x);

    delete[] x;

    std::cout << str << std::endl;
}
Was it helpful?

Solution

It should be fine:
But I would suggest using std::vector rather than newing an array of char:

std::vector<char>  x(len+1);
strcpy(&x[0], getenv("PATH"));

The reason I would do this is that the method assign() can potentially throw an exception. As such the delete may not be called and thus you could leak in the presence of an exception. Using the vector you grantee the memory is cleaned up because of RAII.

OTHER TIPS

Not related to the leak, but if you know the length prefer strncpy over strcpy

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top