3 ms·
I think the model that Free Pascal uses could be adapted to C. It's a reference counted, counted string of bytes. The pointer to the string actually points past
by mikewarot 4y ago
I think the model that Free Pascal uses could be adapted to C. It's a reference counted, counted string of bytes. The pointer to the string actually points past the allocation, reference count, length, etc.. at the first byte of the string. There is a \0 added on the end for safety when passing to OS calls.
Code to modify the string does a copy, decrement the ref count of the original, and then modify of the new string.
Copies of a string are essentially free. You can return them from functions, etc. with no worry about allocation. The run-time handles all of that.
In C, there are mechanisms for running macros when a variable goes out of scope, those could be used to decrement the reference counter to a string used locally inside a function. (Returning the string would need to increase it's ref count first, of course)