valgrind 识别的内存泄漏涉及使用 malloc 到 return 通过 std::string 编辑的字符串 return

Memory leak identified by valgrind involving use of malloc to return a string that was returned via a std::string

我一直在我的 python (ctypes) 接口中点击 'memory problems' 到 c++ 库。所以我 运行 我的 C++/C API 通过 valgrind 进行测试,这表明以下函数有问题:


    char *PhysicalEntity_str(PhysicalEntity *physical_entity_ptr, const char *format, const char *base_uri) {
        std::string str = physical_entity_ptr->toTriples().str(format, base_uri);
        char *cstr = (char *) malloc(str.size());
        strcpy(cstr, str.c_str());
        return cstr;
    }

具体来说,valgrind吐出来

有人可以解释原因并建议解决方法吗?谢谢。

char *cstr = (char *) malloc(str.size());

这个函数分配内存。如果返回的指针从未用 free 释放,则意味着内存已泄漏。

suggest a workaround?

取消分配您分配的所有内容。

如果避免使用裸拥有指针,这会更容易。请改用智能指针和容器。


就是说,我没有看到 valgrind 在图像中提及任何有关内存泄漏的信息。相反,它说 "invalid read of size 1".

 strcpy(cstr, str.c_str());

此行的行为未定义。这总是溢出分配的缓冲区。至少必须分配 str.size() + 1 以使空终止符适合缓冲区。


P.S。不要在 C++ 中使用 malloc。请改用 newnew[]。或者,如果可能,std::stringstd::vectorstd::make_unique