c++ - 在缓冲区之间移动字节时出现意外结果

标签 c++ memory vector

我正在使用 C++ 开发一个函数,其目的是将 num_bytes 从一个 vector 移动到另一个 vector 。

这是我函数的相关部分

// Grab a pointer to the vector currently in use
std::vector<unsigned char> *bytes = &currentBuffer();

// Calculate un-parsed data in current vector                             
size_t num_bytes = static_cast<size_t>(currentBuffer().size() - pos_);

// Added in to test that it is working
std::cout << "Byte before: " << (*bytes)[pos_] << std::endl;

// Move num_bytes from pos_ in currentVector to [0] in otherBuffer
if (num_bytes) {                                              
   memmove(&(otherBuffer()[0]), &((*bytes)[pos_]), num_bytes);
}                                                             

// I now want to use otherBuffer as currentBuffer
bytes = &otherBuffer();                                            

// Reset size of new buffer
bytes->resize(num_bytes);                                     

// Reset position of new buffer
pos_ = 0;

// Added in to test that it is working                                   
std::cout << "Byte after: " << (*bytes)[pos_] << std::endl;

当我使用真实数据运行它时,我从两个 cout 语句中得到两个不同的结果,理想情况下是 currentVector[pos_]otherVector[0] 的字节值> 在 memmove 之后应该是一样的。

知道哪里出了问题吗?我认为错误在 memmove 中,但我不知道它可能是什么。

谢谢!

最佳答案

您需要在将数据复制到缓冲区之前调整其大小,否则您可能会写入超出其他 vector 的内部分配缓冲区的内容。

但是,使用经典的 C++ 方法会更好:

otherBuffer().assign(currentBuffer().begin() + pos, currentBuffer().end());

所有你需要的 - 没有调整大小,没有 memmove(memcpy 在这种情况下可能会更有效......)。

关于c++ - 在缓冲区之间移动字节时出现意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38594718/

相关文章:

c++ - 错误 LNK2019 : unresolved external symbol

c++ - 动态分配的内存未在 SSE 中对齐

c++ - nvcc、gcc、clang 和 msvc "respect"在结构中使用 __restrict__ 关键字吗?

c++ - 删除重复项和对 vector 进行排序的最有效方法是什么?

performance - MATLAB 矢量化 : computing a neighborhood matrix

c++ - vector 迭代器在 for 循环中不可取消引用

c++ - 调用模板函数和非模板函数时的优先级是什么?

c++ - 切线,条件

postgresql - Apache solr 5.3.1 内存不足

c - 有时会绕过 gcc 内存 Hook 吗?