Reputation: 3453
I am working with a network API that returns a list of 1 or more messages into a buffer I provide it. A typical buffer looks like this upon return:
|B|message 1|S|message 2|S|message 3|E|
Where |B| is a character indicating begin, |S| is a separator, and |E| is the end. The messages can be of varying length and number. What I would like to do is traverse this buffer once and split it into its (in this case) 3 component messages, and send something like a std::unique_ptr<char*>
out to code that will process each individual message, and let the unique_ptr take care of releasing the memory. But I'd like to do so without copying these messages out of their buffer and into smaller ones.
Is there a technique I can use to, effectively, sub-allocate the buffer into new, smaller heap blocks and still get the benefit of automatic cleanup?
Upvotes: 0
Views: 216
Reputation: 12943
There's no such a thing as "suballocating" a buffer, at least for most implementations of allocation mechanisms (i.e. heaps).
As a simple solution I'd suggest you to work with shared pointer to the whole buffer, plus the pointer (or offset) and size of the found message.
That is, something like this.
struct MsgPtr
{
shared_ptr<Buffer> m_Buf;
char* m_pMsg;
size_t m_nMsgSize;
};
This should be ok in case you don't intend to keep the parsed messages in memory for a long time.
Upvotes: 2