【问题标题】:Memory leak when using smart pointers使用智能指针时的内存泄漏
【发布时间】:2014-01-30 20:42:00
【问题描述】:

考虑以下函数:

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);
}

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

我的一个同行顺便说他认为这会泄漏内存,但他没有时间详细说明,我没有看到。任何人都可以发现它,如果可以,请解释我应该如何解决它?我可能有我的眼罩。

【问题讨论】:

  • 如果wcstombs_s 失败了怎么办?
  • 如果有选择,返回std::string 会更有意义。但听起来你别无选择。
  • RAII:new的结果应该直接放在unique_ptr中。

标签: c++ memory-leaks


【解决方案1】:

这不一定是泄漏,但它是未定义的行为。您使用new[] 创建了char 数组,但unique_ptr&lt;char&gt; 将调用delete,而不是delete[] 来释放内存。请改用unique_ptr&lt;char[]&gt;

此外,您的转化可能并不总是如您所愿。您应该对wcstombs_s 进行两次调用,在第一次调用中将nullptr 作为第二个参数。这将返回输出字符串中所需的字符数。

wcstombs_s(&charsConverted, nullptr, 0, outputWide, suffix.length());

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

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

【讨论】:

    猜你喜欢
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    相关资源
    最近更新 更多