Char * reallocation in C++
I need to store a certain amount of data in the "char *" in C++, because I wa开发者_开发技巧nt 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++?
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
}
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.
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.
精彩评论