wakey
wakey

Reputation: 2409

Unexpected result when moving bytes between buffers

I am working on a function in c++ where the intent is to move num_bytes from one vector to another.

This is the relevent portion of my function

// 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;

When I run this using real data I am getting two different results from the two cout statments, where ideally the byte value at currentVector[pos_] and otherVector[0] should be the same after the memmove.

Any clue what could be going wrong? I think the error is within memmove however I cannot figure out what it could be.

Thanks!

Upvotes: 0

Views: 69

Answers (2)

Aconcagua
Aconcagua

Reputation: 25536

You need to resize the buffer before you copy data to it, otherwise you risk writing beyond the internally allocated buffer of your other vector.

You'd be better off, however, using a classic C++ approach:

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

All you need - no resize, no memmove (memcpy would probably have been more efficient in this case anyway...).

Upvotes: 4

Robᵩ
Robᵩ

Reputation: 168786

You need to call resize() before the memmove(), not after.

Try this:

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

Upvotes: 1

Related Questions