🔧 Fix String.Create Leaving Unintended Null Characters in the Result Because the Callback Wrote Fewer Characters Than the Requested Length
String.Create’s callback-based overload (the one taking a length, a state object, and a SpanAction delegate) allocates a string of exactly the requested length up front and hands your callback a mutable character span over that already-allocated buffer, trusting the callback to fill every position before the string is handed back as an ordinary, immutable System.String. The API’s contract is that the callback is responsible for writing to the entire span; it isn’t an auto-sized buffer that trims itself down to whatever you actually wrote, and a callback that writes fewer characters than length promised — because it under-calculated the needed length, or because a conditional branch inside it skips writing to part of the span under some input — doesn’t produce a short string or throw an error, it produces a string of exactly the originally requested length with whatever was left in the backing memory (ordinarily the zero/null character for freshly allocated memory) sitting in the positions the callback never touched.
🔎 The Problem
public static string FormatCode(int prefix, int suffix)
{
string prefixStr = prefix.ToString();
string suffixStr = suffix.ToString();
// Mistake: length calculation assumes a fixed-width suffix,
// but suffix can legitimately be shorter (e.g. suffix = 7
// formats as "7", not "0007")
int totalLength = prefixStr.Length + 1 + 4; // assumes 4-digit suffix
return string.Create(totalLength, (prefixStr, suffixStr), (span, state) =>
{
state.prefixStr.AsSpan().CopyTo(span);
span[state.prefixStr.Length] = '-';
// Only writes suffixStr.Length characters here, which can
// be LESS than the 4 reserved - the callback does nothing
// for whatever positions are left over at the end
state.suffixStr.AsSpan().CopyTo(
span.Slice(state.prefixStr.Length + 1));
});
}
string code = FormatCode(482, 7);
Console.WriteLine(code.Length); // 8 (prefix "482" + "-" + 4 reserved)
Console.WriteLine(code); // "482-7" followed by three
// untouched positions still
// hold the allocator's
// leftover null characters,
// invisible in most console
// output but very much
// present in the string's
// actual character data
✅ Fix: Make the Callback Fill Every Position It Was Given, Every Time
- Compute length from the actual runtime values being written (prefixStr.Length + 1 + suffixStr.Length here), not from an assumed fixed width, so the requested length and what the callback actually writes always match exactly regardless of input.
- If a value’s formatted width genuinely can vary and you want fixed-width output, explicitly pad inside the callback (writing literal padding characters into the unused span positions) rather than leaving them untouched and hoping the backing memory happens to contain something harmless.
- Add a debug-only assertion inside the callback that checks every branch actually advances to the full span length before returning, which catches a conditional path that silently skips writing part of the span during development rather than shipping a string with embedded null characters to production.
🚨 Why This Is Dangerous
- A string with trailing or embedded null characters looks completely normal when printed to a console or most UI text controls, but can fail string comparisons, break when passed to native interop or file I/O that treats a null character as a terminator, or silently corrupt anything downstream that assumes string.Length characters of real content.
string.Create hands you a buffer of exactly the length you asked for and trusts you to fill every position in it — it has no way to know your callback meant to write less, so whatever you leave untouched just stays whatever the allocator happened to put there.
