views:

166

answers:

2

I am using HDF5 to read a string in to 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;
}
+3  A: 

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.

Martin York
+1. Because of the RAII mention.
paercebal
I suggest using std::string rather than std::vector, since the OP is using `char *` rather than `unsigned char *`.
Thomas Matthews
Hmm... while what you say is totally valid, does it even attempt to answer the question?
Michael Krelin - hacker
@Michael: Are you serious? It explicitly answers the question in the first sentence.
Martin York
@Thomas: That string is an alternative to vector. BUT I am using char (not unsigned char). Also string also implies more about the data at them moment we are just using it as a buffer. Also in the current version of the standard there is no guarantee that string has contiguous storage (though it may be implied and is made explicit in the next standard).
Martin York
Martin, indeed it does. But I think OP wants explanations (Honestly, I have no idea and not intrigued enough to find out).
Michael Krelin - hacker
+2  A: 

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

orip
Remember that `strcpy` will copy all characters until it finds a null terminating character, an illegal address is hit, or the world ends.
Thomas Matthews
A nice feature of `std::string` is that the copying functionality is built in and *tested*.
Thomas Matthews