对 delete[] 的 Malloc 调用在 TotalView 中显示为内存泄漏
我正在使用 HDF5 将字符串读入由 new[]
分配的 char*
中。然后,我使用 string::assign() 调用将此数据复制到我真正想要的位置。然后我对该 char* 调用 delete[]
。这显示为使用 TotalView 的内存泄漏的根源。它显示了 stdlibc++ 中 delete[]
下对 replace_safe
、mutate
、create
和 malloc 的损坏调用
。这是怎么回事,这真的是内存泄漏吗?我也在这里设置了 GLIBCXX_FORCE_NEW=1
。
下面是复制这种情况的示例代码。请注意,valgrind 显示没有泄漏,如果我不在 cout 调用之前放置断点,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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
应该没问题:
但我建议使用 std::vector 而不是新建一个 char 数组:
我这样做的原因是方法 allocate() 可能会抛出异常。因此,可能不会调用删除,因此在出现异常时可能会泄漏。使用您授予的向量,由于 RAII,内存会被清理。
It should be fine:
But I would suggest using std::vector rather than newing an array of char:
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.
与泄漏无关,但如果您知道长度,则更喜欢
strncpy
而不是strcpy
Not related to the leak, but if you know the length prefer
strncpy
overstrcpy