Chapter 9. Easier Text Handling

I believe that in the end the word will break cement.

Pussy Riot, paraphrasing Aleksandr Solzhenitsyn in a statement on August 8, 2012

A string of letters is an array of indeterminate length, and automatically allocated arrays (allocated on the stack) can’t be resized, and that in a nutshell is the problem with text in C. Fortunately, many others before us have already faced this problem and produced at least partial solutions. A handful of C-standard and POSIX-standard functions are sufficient to handle many of our string-building needs.

Also, C was designed in the 1970s, before the invention of non-English languages. Again, with the right functions (and the right understanding of how language is encoded), C’s original focus on English is not a real problem.

Making String Handling Less Painful with asprintf

The asprintf function allocates the amount of string space you will need, and then fills the string. That means you never really have to worry about string-allocating again.

asprintf is not part of the C standard, but it’s available on systems with the GNU or BSD standard library, which covers a big range of users. Further, the GNU Libiberty library provides a version of asprintf that you can either cut and paste into your own code base or call from the library with a -liberty flag for the linker. Libiberty ships with some systems with no native asprintf, like MSYS for Windows. And if cutting and pasting from libiberty is not an option, I’ll ...

Get 21st Century C, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.