调用linearize后奇怪的boost循环缓冲行为

Strange boost circular buffer behaviour after calling linearize

本文关键字:boost 循环缓冲 linearize 调用      更新时间:2023-10-16

我已经在我的boost::circular_buffer上实现了一个提取方法,它只是将n元素复制到destination向量,然后从循环缓冲区中删除这n个元素(因此其内部指针被更新,标记可以再次写入的地方):

void CircularBuffer::extract(const unsigned int n, vector<complex<float>> *destination){
    // Wait until the buffer is not empty
    std::unique_lock<mutex> l(lock);
    notEmpty.wait(l, [this, n](){
        return (int)(circularBuffer.size() - n) >= 0;
    });
    // We must copy n elements from a linearized version of the buffer
    memcpy(destination, circularBuffer.linearize(), n);
    // Remove extracted elements from circular buffer
    circularBuffer.erase(circularBuffer.begin(), circularBuffer.begin() + n); //SIGSEGV
    // Not full any more
    notFull.notify_one();
}

当调用erase方法时,我得到一个分割错误。

我使用以下大小:

n = 9000
circularBuffer.size() = 9000 (at the moment when extract method is called)
circularBUffer.capacity() = 90000

但是,一旦执行memcpy行,我猜是因为linearize调用,一切都是混乱的,调试器显示:

circularBuffer.size() = 3238197033 (Hex: Hex:0xc102f729)
circularBUffer.capacity() = 18446744073434141805 (Hex:0xffffffffef95946d)

我可能不明白线性化方法是如何工作的,但它看起来很奇怪。

如果我继续,并且调用erase方法,则会引发分割错误并结束程序。如果我擦除的数据比缓冲区容量多,我可以理解,但事实并非如此。

帮忙吗?

您的记忆有误。您正在将数据复制到vector对象本身的地址中,而不是将其复制到向量指向的位置。请确保在调用此函数之前调用vector::reserve,以避免不必要的内存取消分配和分配。

我将把这个函数重写为:
    #include <iterator>
    void CircularBuffer::extract(const unsigned int n, 
                               vector<complex<float>>& destination)
    {
        // Wait until the buffer is not empty
        std::unique_lock<mutex> l(lock);
        notEmpty.wait(l, [this, n](){
            return (int)(circularBuffer.size() - n) >= 0;
        });
        auto cb_ptr = circularBuffer.linearize();
        assert (cb_ptr);
        std::copy(cb_ptr, cb_ptr + n, std::back_inserter(destination));
        circularBuffer.erase(circularBuffer.begin(), circularBuffer.begin() + n); 
        // Not full any more
        notFull.notify_one();
    }