C Strings Are Terrible — Build String Views Instead
- https://www.youtube.com/watch?v=y8PLpDgZc0E
- Original title: C Strings are Terrible!
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;sizeofproves 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_rightjust decrementscount;SV_chop_leftadvances the base pointer and decrementscount. Both are non-destructive and allocation-free. Guard againstcount =0= (size_t underflow) and clampnto the size when chopping multiple characters.
Interop and printing
SV(cstr)conversion is trivial (point at same base,strlenfor size). The reverse (SV → C string) is hard: you must allocate and copy to append a null terminator.printfignores 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_trimchop whitespace by repeatedly chopping while the edge characterisspace(and the view is non-empty).sv_chop_by_delimscans 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.