使用智能指针时内存泄漏

Jus*_* R. 1 c++ memory-leaks

考虑以下功能:

unique_ptr<char> f(const wstring key, const unsigned int length)
{
    assert(length <= key.length());
    const wstring suffix = key.substr(length, key.length() - length);
    const size_t outputSize = suffix.length() + 1; // +1 for null terminator
    char * output = new char[outputSize];
    size_t charsConverted = 0;
    const wchar_t * outputWide = suffix.c_str();
    wcstombs_s(&charsConverted, output, outputSize, outputWide, suffix.length());
    return unique_ptr<char>(output);
}
Run Code Online (Sandbox Code Playgroud)

这里的目的是接受一个wstring,length从最后选择字符,并将它们作为C样式的字符串返回,该字符串包含在unique_ptr中(根据另一个库的要求 - 我当然没有选择那种类型:)).

我的一位同事顺便说过,他认为这会泄漏记忆,但他没有时间详细说明,我也看不到.任何人都可以发现它,如果是这样解释我应该怎么解决它?我可能有我的眼罩.

Pra*_*ian 10

它不一定是泄漏,但它是未定义的行为.您char使用new[]但是unique_ptr<char>将调用delete而不是delete[]释放内存来创建数组.请unique_ptr<char[]>改用.

此外,您的转换可能并不总是按照您希望的方式运行.您应该wcstombs_s在第一个传递中进行2次调用,nullptr作为第二个参数.这将返回输出字符串中所需的字符数.

wcstombs_s(&charsConverted, nullptr, 0, outputWide, suffix.length());
Run Code Online (Sandbox Code Playgroud)

检查返回值,然后使用存储的结果charsConverted分配输出缓冲区.

auto output = std::unique_ptr<char[]>(new char[charsConverted]);
// now use output.get() to get access to the raw pointer
Run Code Online (Sandbox Code Playgroud)