4 ms·
uh, so not a single person has mentioned memory allocation issues yet? the pointer to the 0 terminated string could have been to a statically allocated array o
by dusklight 16y ago
uh, so not a single person has mentioned memory allocation issues yet?
the pointer to the 0 terminated string could have been to a statically allocated array or memory allocated from the heap using malloc. If you just shorten the string without reallocating the memory, the extra bytes that got condensed are still marked as allocated and are wasted.
- jacquesm 16y agoThat's pretty obvious, but since that was the requirement that's what you do. For all you know the length of the original string is kept around somewhere for future reference when the buffer is re-used, it's not uncommon for buffers used like this to be limited to some fixed size larger than the maximum expected string length + 1 for the terminating nul char, and to have a string copied in to a buffer for processing. You're in deep trouble when you try to insert stuff into strings like that though... The bytes that got condensed and are wasted would be wasted even worse in the way you describe, if you re-allocate the memory then you'll have to free the original one, leaving the larger portion sitting unused, instead of just a few bytes... Sure, that could be re-used by some other call to the allocator by a different part of the program, but the most important issue here is that that was not what was specified. Whoever spec'd it needs it like that, so that's what gets built.