gpt4 book ai didi

c++ - 带有嵌入式竞技场的堆栈分配器问题

转载 作者:搜寻专家 更新时间:2023-10-31 00:34:53 24 4
gpt4 key购买 nike

我在使用 Howard Hinnant 的 stack-based allocator 时遇到崩溃, 都在带有 Clang 3.4 的 64 位 Linux 和 MacOS。这是一个最小的例子在容器的析构函数中触发崩溃:

#include <vector>
#include "stack_alloc.h"

template <template <typename...> class C, typename T, size_t N>
using stack_container = C<T, stack_alloc<T, N>>;

using stack_vector = stack_container<std::vector, size_t, 4>;

int main()
{
auto s = stack_vector{1, 2, 3};
auto m = std::move(s);
}

编译如下:

clang++ -std=c++11 -stdlib=libc++ -g -Wall crash.cc && ./a.out

您知道为什么会发生这种崩溃吗?我也试过根据 arena 实现重新实现 stack_alloc short_alloc ,但在 move 基于堆栈的容器时我仍然遇到崩溃。

这是一个 Linux 回溯:

#0  _int_free (av=0x394f5b8760 <main_arena>, p=0x7fffffffe0f0, have_lock=0) at malloc.c:3901
#1 0x00000000004013eb in stack_alloc<unsigned long, 4ul>::deallocate (this=0x7fffffffe080, p=0x7fffffffe100, n=3)
at ./stack_alloc.h:71
#2 0x0000000000401343 in capacity (this=0x7fffffffe060, this=0x7fffffffe060, __a=..., __p=0x7fffffffe100, __n=3)
at .../include/c++/v1/memory:1443
#3 std::__1::__vector_base<unsigned long, stack_alloc<unsigned long, 4> >::~__vector_base (this=0x7fffffffe060)
at .../include/c++/v1/vector:476
#4 0x0000000000400fa5 in std::__1::vector<unsigned long, stack_alloc<unsigned long, 4> >::~vector (this=0x7fffffffe060)
at .../include/c++/v1/vector:481
#5 0x0000000000400f6e in main () at crash.cc:13

我很想(i) 是否有人可以重现该错误,以及(ii) 如何修复它。

最佳答案

您正在使用不符合规范的 C++11 stack_alloc。作为希南特 himself wrote ,

I've updated this article with a new allocator that is fully C++11 conforming. The allocator it replaces was not fully C++03 nor C++11 conforming because copies were not equal.

更正后的版本名为 short_alloc 并且是 found here .

使用需要将堆栈缓冲区放在分配器之外(使用 Hinnant's notation ):

int main()
{
arena<N> a; // change N to required space
auto s = SmallVector({1, 2, 3}, Alloc{a});
auto m = std::move(s);
}

关于c++ - 带有嵌入式竞技场的堆栈分配器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25193969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com