Chapter 9. Text
I believe that in the end the word will break cement.
—Pussy Riot, paraphrasing Aleksandr Solzhenitsyn in a statement on 8 August 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-allocing
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 cut and paste
into your own code base; see the next section.
The old way made people homicidal (or suicidal, depending on temperament), because they first had to get the length of the string they were about to fill, allocate space, and then actually write to the space. Don’t forget ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access