首页 > 解决方案 > Google Sparsehash 在不可复制的类型上使用 realloc()

问题描述

考虑这个简单的程序:

#include <string>
#include <sparsehash/dense_hash_map>

int main()
{
    google::dense_hash_map<std::string, int> map;
    map["foo"] = 0;
}

使用 GCC 8.2 和-Wclass-memaccess(或-Wall)编译会产生警告:

sparsehash/internal/libc_allocator_with_realloc.h:68:40: warning:
‘void* realloc(void*, size_t)’ moving an object of non-trivially copyable type
    ‘struct std::pair<const std::__cxx11::basic_string<char>, int>’;
use ‘new’ and ‘delete’ instead [-Wclass-memaccess]
    return static_cast<pointer>(realloc(p, n * sizeof(value_type)));
                                ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~

问题是:

  1. 它是未定义的行为吗?
  2. 您能否建议可以应用于应用程序代码的修复或解决方法(不是通过更改 Sparsehash 或避免使用它)?
  3. (奖励积分)你能构造一个实际上因此而行为不端的程序(使用 std::string 或你自己的非平凡类型)吗?到目前为止,我在使用 std::string 作为键类型的代码中没有看到任何问题,尽管 std::string 必须是非常常用的键类型。

我在这里提出了一个问题:https ://github.com/sparsehash/sparsehash/issues/149

标签: c++undefined-behaviorreallocgcc8sparsehash

解决方案


1. 它是未定义的行为吗? 是的。永远不要使用 realloc() 复制对象,因为有时它们具有指向资源的内部指针。当 2 个不同的对象运行其析构函数时,问题就会出现。现在,同一资源发生了双重释放,完全没有。

2. 您能否建议可以应用于应用程序代码的修复或解决方法(不是通过更改 Sparsehash 或避免使用它)?

尝试

#include <memory>

并换线

google::dense_hash_map<std::string, int> map;

google::dense_hash_map<std::string, int, std::hash<std::string>, std::equal_to<std::string>, std::allocator> map;

现在,它不会使用谷歌的分配器libc_allocator_with_realloc

3.(加分)你能构造一个实际上因此而行为不端的程序(使用 std::string 或你自己的非平凡类型)吗?到目前为止,我在使用 std::string 作为键类型的代码中没有看到任何问题,尽管 std::string 必须是非常常用的键类型。

不容易。因为您正试图引起未定义的行为。在您的测试程序中,我将提供长度至少为 32 个字符的字符串,因此不会启动小字符串优化。并且可以在 gcc 的堆中进行一些测试以查看它是否已损坏。见 1


推荐阅读