c++ - Avoiding memory leaks while mutating c-strings -
For educational purposes, I am using seestring in some testing programs. I would like to shorten strings with a placeholder like "...".
That is, "very long string"
will be "enough one."
If my maximum length is set to 13. Also, I do not want to delete the original string - so a small string should be copied.
This (static) method is below which I came up with. My question is that Should the memory allocated class for my short string be also responsible for freeing it? Now what I do is to store the returned string in a different "user class" and to free the memory that user class.
const char * TextHelper :: shortenWithPlaceholder (const char * text, size_t newSize) {char * short = new char [newSize + 1]; If (new size & lt; = 3) {strncpy_s (small, new size + 1, ".", New size); } Other {strncpy_s (small, new size + 1, text, new size -3); Strncat_s (small, new size + 1, "...", 3); } Returned; }
The standard approach to such functions is that the user must pass nearby [] Buffer You see it in functions such as sprintf ()
, for example, to take a destination buffer as a parameter, to keep the caller in full memory management problem in one place. Allows to be responsible for allocation and release of memory.
Comments
Post a Comment