The most common way of creating an
but there is also a two-phase creation pattern:
First you call
to create a buffer for a future string.
You then fill the buffer with stringy goodness
and then call
to convert it to a real
(Or you can call
to change your mind and pretend it never happened.)
The rule for managing the buffer returned by
is that you are expected to write exactly
length code units into the buffer.
The system already put a terminating null after the end of the
your job is to fill the buffer with the string contents.
For example, if you want to use two-phase creation to create
you would call
length = 5.
Into the resulting buffer,
you write the characters
and that's all.
The system already stored the terminating null.
This particular formulation of the rules is important in the
length = 0.¹
Since the representation of an
of length zero is the null pointer,
there is no actual buffer.
What happens is that the system uses a single preallocated
buffer (consisting of just a null terminator)
to represent the buffer for all zero-length strings.
If you call
you get a pointer to that preallocated buffer.²
Since you passed a length of zero,
you are expected to write zero characters to the buffer;
in other words,
you are expected to do nothing at all with the buffer.
And of course since
HSTRINGs are immutable,
your permission to modify the buffer ends once you
promote the buffer to a string.
Once it's been promoted to a string, the entire buffer
Another way of interpreting this corner case is to say
"Don't bother calling
with a string of length zero.
Otherwise, go ahead and call it, and you can write that null
terminator if you like."
Arguably, to accommodate the possibiltiy of somebody writing
that null terminator,
it should return a preallocated writable buffer
just large enough to hold that null terminator.
It could be the high 16 bits of the