kiran
kiran

Reputation: 41

working with boost::shared_array

I have a use case where i need to pass the boost::shared_array every time. If the buffer is not completely used i want to create a new pointer with same memory space but from the point where the date is already written

sample code :

  boost::shared_array<uint8_t> buffer;
  boost::shared_array<uint8_t> placeHolder;
  buffer.reset(new boost::uint8_t[1024 * 1024]);
  placeHolder = buffer;
  uint32_t maxSize = 1024 * 1024;
  uint32_t dataCopied = 0;
  while(dataCopied < 1024 * 1024)
  {
     uint32_t bytesWritten = getData(placeHolder, maxSize); //This call might give any size of data less than  boost::shared_array<uint8_t> buffer;
     placeHolder = boost::shared_array<uint8_t>(buffer.get() + bytesWritten);
  }

unfortunately this is crashing for me with out any clue. Any suggestions whats going wrong in the concept ?

Upvotes: 1

Views: 2411

Answers (1)

Arpegius
Arpegius

Reputation: 5887

You cannot use boost::shared_array in that way. This line makes everything go wrong:

placeHolder = boost::shared_array<uint8_t>(buffer.get() + bytesWritten)

You create new shared_array that try to delete[] the offseted pointer, right after next loop, making undefined behavior. You should not use shared pointers here, but if must (like in callbacks), there is a way of doing it with std::shared_ptr using the aliasing constructor:

placeHolder = std::shared_ptr<uint8_t>(
                  placeHolder, 
                  placeHolder.get() + bytesWritten); 

It will keep the shared state and change only the pointer, data buffer will be deleted only once.

Working example http://melpon.org/wandbox/permlink/9WP08ReJAijjCMHR

If you just absolutely have to use boost::shared_array you could use deleter that does nothing, but that's just wrong, and if you use that solution you should feel wrong. No thanks: http://melpon.org/wandbox/permlink/BR44arnH60znibAR

Upvotes: 2

Related Questions