A Question about new vs malloc and realloc.

D

DrBob

gcc 3.3 on Mac OS X.

I need to dynamically grow a buffer by concatinating raw binary data
in chunks.

How do I use 'new' to grow the buffer size as its contents grow? I
know this can be done with realloc.. (realloc will give you a new
pointer to a new buffer that has the same contents as the previous
buffer and will free the previous buffer for you).

Perhaps there is a different class I could be using?
 
V

Victor Bazarov

DrBob said:
gcc 3.3 on Mac OS X.

I need to dynamically grow a buffer by concatinating raw binary data
in chunks.

How do I use 'new' to grow the buffer size as its contents grow? I
know this can be done with realloc.. (realloc will give you a new
pointer to a new buffer that has the same contents as the previous
buffer and will free the previous buffer for you).


Use 'new' to allocate another "buffer", copy the original "buffer"
there, then add whatever is needed. Then use 'delete' to free the
original.
Perhaps there is a different class I could be using?

Different class of what?
 
U

Unforgiven

DrBob said:
I need to dynamically grow a buffer by concatinating raw binary data
in chunks.

How do I use 'new' to grow the buffer size as its contents grow? I
know this can be done with realloc.. (realloc will give you a new
pointer to a new buffer that has the same contents as the previous
buffer and will free the previous buffer for you).

realloc is basically a sequence of malloc new buffer, memcpy, free old
buffer. So you can just as easily do that yourself with new: create new
buffer, memcpy, delete old buffer.

Note that this has the danger of becoming a real performancekiller as your
buffer grows, since more and more data will need to be copied everytime you
grow. The best way to avoid too much copying if you must do this is probably
to double your buffer everytime, instead of just adding a single chunk size.
Perhaps there is a different class I could be using?

std::vector<unsigned char> will do all of the above for you with no
additional effort. It will double the buffer whenever it runs out of space.

A better approach might be keeping all the separate buffers in a
std::list<unsigned char*> or std::list<std::vector<unsigned char> >, then
when you have them all simply create a single buffer that's large enough for
all buffers and copy all the individual buffers into it. This minimizes
resizing and copying. It depends on what you're trying to do though.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top