c++ - munmap_chunk:使用 std::vector 更改数据存储位置时的无效指针

标签 c++ c++11 vector

我正在为微 Controller 编写程序,我需要将 vector 数据分配到内存中的特定位置(将其存储在闪存中)。

#include <iostream>
#include <vector>

struct struct_gauss {
    int mean;
    int sigma;
};

std::vector<struct_gauss> makeVector(size_t size, void* address, void* &endAddress) {
    std::vector<struct_gauss> dummy;
    struct_gauss **dummyPointer = (struct_gauss **) &dummy; // Address to metavalue of std::vector dummy (exists of 3 pointers)
    *dummyPointer = (struct_gauss *) address; // Point data of dummy to requested address
    *(dummyPointer+1) = ((*dummyPointer)+size);
    *(dummyPointer+2) = *(dummyPointer+1);
    endAddress = (void*) &(*dummy.end());
    return dummy;
}

int main()
{
    void* dummyPointer1 = malloc(1);
    void* dummyPointer2;
    auto vector1 = makeVector(10, (void*) dummyPointer1, dummyPointer2);
    auto vector2 = makeVector(10, (void*) dummyPointer2, dummyPointer2);
    vector1[9].mean = 10;
    vector2[0].mean = 5;
    std::cout<<"address of vector2 begin = "<< &(*vector2.begin())<<std::endl;
    std::cout<<"vector1[9].mean = "<<vector1[9].mean<<"; vector2[0].mean = "<<vector2[0].mean<<std::endl;

    return 0;
}

这将创建 2 个大小为 10 个值的 vector ,它们从指针 dummyPointer1 开始背靠背。但是,当运行它时,出现以下错误:

address of vector2 begin = 0xf42c70    
vector1[9].mean = 10; vector2[0].mean = 5                                                                                                                                    
*** Error in `/home/a.out': munmap_chunk(): invalid pointer: 0x0000000000f42c70 ***                                                                           
Aborted 

他在退出 main() 函数时出错,因为他无法释放 vector2。

这是为什么呢?我怎样才能解决这个问题? 有没有更好的办法?

附言我可以将 vector 的指针(元值)保存在 RAM 中,但如果更好的话,也可以将它们写入闪存。使用 Flash 是因为我的 RAM 有限并且这些 vector 仅在从外部加载新模型时写入。

最佳答案

有很多东西看起来很可怕,我为直言不讳道歉,但在这种情况下我的意思是“可怕”。

std::vector<struct_gauss> makeVector(size_t size, void* address, void* &endAddress) {
    std::vector<struct_gauss> dummy;
    struct_gauss **dummyPointer = (struct_gauss **) &dummy; // Address to metavalue of std::vector dummy (exists of 3 pointers)
    *dummyPointer = (struct_gauss *) address; // Point data of dummy to requested address
    *(dummyPointer+1) = ((*dummyPointer)+size);
    *(dummyPointer+2) = *(dummyPointer+1);
    endAddress = (void*) &(*dummy.end());
    return dummy;
}

这段代码看起来没有任何安全或可取之处。关于如何在内存中构造 std::vector 对象似乎有很多假设,即使您的假设是正确的,您仍然未能正确构造 std::vector 对象以符合标准的方式。

int main()
{
    void* dummyPointer1 = malloc(1);
    void* dummyPointer2;
    auto vector1 = makeVector(10, (void*) dummyPointer1, dummyPointer2);
    auto vector2 = makeVector(10, (void*) dummyPointer2, dummyPointer2);

这是完全错误的。您正在分配一个字节来存储 vector ,期望对象存储 10 个字节,但实际上您没有为底层数组分配空间。

简而言之,我想你已经打了XY-Problem ,句号。您要解决的问题是“如何让 std::vector 从闪存中分配内存”

通常解决这类问题的方法是使用自定义分配器。

template<typename T>
struct allocator {
    typedef size_t size_type; 
    typedef ptrdiff_t difference_type;
    typedef T * pointer;
    typedef T const& const_pointer;
    typedef T& reference;
    typedef T const& const_reference;
    typedef T value_type;
    pointer allocate(size_t size) {
        void * mem = micro_controller_api::allocate_flash_memory(size); //I don't know what your API looks like

        //You'll need something else if you're not able to throw exceptions in your code.
        if(!mem) throw std::bad_alloc(); 

        //On its own, this would be unsafe, but std::vector uses placement new with its memory,
        //so you don't need to worry that the cast here would risk some undefined behavior.
        return static_cast<pointer>(mem);
    }
    void deallocate(pointer p, size_t) noexcept { micro_controller_api::free_flash_memory(static_cast<void*>(p)); }

    allocator() = default;
    template<typename U>
    allocator(allocator<U> const&) {}

    pointer address(reference r) const {return addressof(r);}
    const_pointer address(const_reference r) const {return addressof(r);}

    bool operator==(allocator const&) const {return true;} //All allocators are the same
    bool operator!=(allocator const&) const {return false;}
};

int main() {
    std::vector<struct_gauss, allocator<struct_gauss>> vector1(10);
    std::vector<struct_gauss, allocator<struct_gauss>> vector2(10);
    //Do whatever; vector1 and vector2 are, as far as anyone is concerned, perfectly valid vectors
}

请注意,我以前没有自己编写过分配器,我在这里提供的分配器基于 C++ reference page 上显示的模板。 ,(编辑:我还通过引用 this page 添加了一些内容)所以我可能犯了错误。但希望所有这些足以解决您的问题。

关于c++ - munmap_chunk:使用 std::vector 更改数据存储位置时的无效指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48157527/

相关文章:

c++ - 我在功能逻辑上哪里出错了

c++ - 使用索引 vector 重新排序 vector

c++ - 从 boost::hash 获取 32 位哈希值

c++ - reinterpret_cast - 整数、枚举、指针或成员指针类型的表达式可以转换为它自己的类型

c++ - 是否可以从父类 "this"指针类型强制转换为子类

c++ - C++/CX 中的 [this] 是什么? (Windows 8)

c++ - std::vector<std::vector<Vertex>> 顶点矩阵;在这方面没有申明

c++ - 将 gzip_compressor 与 boost::iostreams::filtering_wostream 一起使用,编译器错误

c++ - 为什么 KMP 失效函数可以在 O(n) 时间内计算出来?

c++ - LLDB如何找到内联函数?