views:

117

answers:

3

Hi,

I need to store a certain amount of data in the "char *" in C++, because I want to avoid std::string to run out of memory, when exceeding max_size(). But the data comes in data blocks from the network so I need to use reallocation every time I get the data block. Is there any elegant solution for char * reallocation and concatenation in C++?

+1  A: 

You could go the C way and use malloc() / realloc(), but realloc() will just allocate a new block, copy the old stuff into the new stuff, and free the old block sometimes anyway. Also it's difficult to use correctly.

You could just allocate a huge buffer and/or grow it exponentially, offsetting severity of the problem.

Or you could use ropes.

Chris Lutz
"You could just allocate a huge buffer and/or grow it exponentially, offsetting severity of the problem." <-- Note: Most `std::string` implementations already do this.
Billy ONeal
@Billy - That's not surprising. I wonder if the OP knows he's going to have allocation problems or if he's prematurely optimizing.
Chris Lutz
Usually, realloc will only have to copy if there's no room in the memory arena after the block (and, of course, this depends entirely on the implementation but all the ones I've read (and the few I've written) optimise for that case).
paxdiablo
+1  A: 

std:vector comes to mind for automatic allocation as the string grows in size. Just allocate a Vector<char> and push_back() chars to your heart's content.

Michael Dorgan
This will be no different than `std::string` 99% of the time, which the OP says he explicitly wants to avoid.
Billy ONeal
+2  A: 

In visual studio, max_size() is 4294967294 chars, roughly 4Gb. It would be interesting if you could tell us how you run the risk of exceeding this many chars.

If the problem does not crop up often, and this is only about making it fail safe then

 myConcatStr(string str1, string str2)
 {
      if (str1.length() + str2.length()) <= str1.max_size() // if there is no overflow problem
           str1.append(str2); // use stl append
      else
           //use alternate method instead or throw an exception
 }
aCuria
Err.. that's 4GiB, not 8.
Billy ONeal
@aCuria: not for a `string` (`sizeof(char)` is 1 by definition). For a `wstring` the size of the element might be 2.
Michael Burr
mybad, edited...
aCuria