YouTube Summaries

← All summaries

C Strings Are Terrible — Build String Views Instead

2026-03-19 Thu ⏱ 28 min @Tsoding

A from-scratch explanation of why null-terminated C strings are a bad foundation and how the "string view" (pointer + length) paradigm fixes it. Tsoding demonstrates that a C string is really just a 64-bit address, shows the concrete pain it causes — you can't trim from the right without destroying data or allocating — then builds a small string-view library (chop, trim, split) live to show how much cleaner and allocation-free string manipulation becomes.

C strings are just pointers

  • A string literal assigned to char * is a 64-bit integer holding an address in memory; sizeof proves it's 8 bytes, not the string length. Dereferencing gives one byte (the first character, e.g. 72 = 'H').
  • The string is "a view on bytes." Adding 1 to the pointer chops a character off the left for free — cheap and non-destructive.

Why C strings are terrible

  • The null terminator makes right-side chopping impossible without destroying data (overwriting a byte with \0).
  • String literals live in a read-only section, so even destructive editing segfaults. To chop from the right you must strdup (malloc + copy), introducing dynamic memory and leaks.
  • Memory leaks only matter for long-running programs (servers, games, media apps); for run-once programs the OS reclaims everything on exit.

String views (pointer + length)

  • Modern languages store two integers: base address + size (a.k.a. string view / string slice). No null terminator needed — the end is implied by the length.
  • SV_chop_right just decrements count; SV_chop_left advances the base pointer and decrements count. Both are non-destructive and allocation-free. Guard against count = 0= (size_t underflow) and clamp n to the size when chopping multiple characters.

Interop and printing

  • SV(cstr) conversion is trivial (point at same base, strlen for size). The reverse (SV → C string) is hard: you must allocate and copy to append a null terminator.
  • printf ignores the view's length; use "%.*s" with the count to print only the viewed window.

Higher-level operations

  • sv_trim_left / sv_trim_right / sv_trim chop whitespace by repeatedly chopping while the edge character isspace (and the view is non-empty).
  • sv_chop_by_delim scans for a delimiter, returns the prefix as a new view and mutates the original to hold the remainder — the building block for splitting/parsing without copying.
  • The payoff: operating on small "windows" over a single buffer is an "insanely powerful paradigm" for parsing files, lines, and words with no allocations.