Hi,
Is it possible to find out if a chars string is full or half full?
I want to use realloc after a malloc, but only if the chars string is almost full...
TY
Hi,
Is it possible to find out if a chars string is full or half full?
I want to use realloc after a malloc, but only if the chars string is almost full...
TY
What exactly does it mean for a string to be full or half full?
EDIT:
Keep track of the number of characters in use (size) and the number of characters for which space is allocated (capacity). When the size is close enough to the capacity, increase the capacity.Originally Posted by Tiago
Last edited by laserlight; 05-25-2010 at 11:25 AM.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Count characters until \0 is reached, and compare the count to the size of the string?
As I said: keep track of the size and capacity.Originally Posted by Tiago
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Well yes, you can reference it directly, but then you are ignoring the possibility that there is a \0 in the array somewhere before that character and that the one you are looking at is garbage.
Or just do like laserlight said and keep track of any changes you make to the string as you go.
If you're not tracking the size already then there's a good chance that you're already in danger of a buffer overflow, or data truncation.
It may go from 40% full to 10% overflowing in a single concatenation. To make sure that doesn't happen, you have to check that the initial length plus the length to concatenate is less than the current size. If not, you need to grow first.
You can't just rely on checking the length after each concatenation.
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"