Dealing with strings in C definitely makes one wish for a simple class-based language, but I'm trying to instead build a convenient string library. My idea is to use immutable strings, with a struct called Rstring
(for "robust string") that has an internal const char* s
and int length
, such that operations like rstring_concat
and rstring_substring
return new Rstring
objects with their own newly malloc
'd character pointers.
Writing up an initial draft of the library, I am pleased with the simplicity and cleanliness of using my library instead of char *
. However, I realized that returning a newly allocated pointer is somewhat of a PITA without a destructor. Each time some operation is done, say via concatenation or substrings, you have some newly allocated memory, and then whichever strings you had before are now hanging around, and probably are useless, so they need to be free
'd, and C has no destructors, so the user is stuck having to manually go around free
ing everything.
Therefore my question is, are there any clever ways to avoid having to make a whole bunch of manual calls to free? Possibly, for example, having internal start
and end
indices in order to have strings which act like small strings, but really contain quite a bit more? I don't know if there's any generally accepted method of doing this, or if people are simply stuck with tedious memory management in C.
Perhaps best, is there any widely-used library for convenient string manipulation in C?