smartstr: an ANSI C (C89) library for easy strings

I am an old school ANSI C programmer who never warmed to C++ with its endless features and countless extensions. To me, a programming language should be simple. ANSI C embodies that simplicity - so much so that it doesn't even provide a "string" type. Instead, developers are left to juggle arrays of characters, which often leads to trouble: buffer overflows when a string grows beyond its allocation, segmentation faults when a nul terminator is forgotten, memory leaks, and more.

Tired of fighting these recurring battles, I created smartstr.

smartstr is a lightweight library designed to shield programmers from the common hazards of string handling in C. It introduces an opaque data type, smartstr_t, along with a set of functions to manage it. With smartstr, you no longer need to worry about manual memory (re)allocation, missing terminators, or wasting CPU cycles just to append one string to another.

By design, smartstr prevents direct tinkering with the underlying character array. Yet it still provides access to a standard, nul-terminated, read-only view of your string whenever you need it.

The goal of smartstr is not only to make string handling safer and easier, but also to do so efficiently. Checking a smartstr's length, concatenating two smartstr strings, or appending data to an existing one are all operations implemented more efficiently than the strcat() and strlen() functions provided by the standard C library.

Examples

/* declare the string - no need to "create" it explicitely if you init it to NULL */
smartstr_t *mystring = NULL;

/* set the string to some initial words */
smartstr_set(&mystring, "Hello, World");

/* append a single character to the string */
smartstr_addc(&mystring, '!');

/* how long is my string? */
size_t slen = smartstr_len(mystring);

/* get a NULL-terminated pointer to your string */
printf("My smart string is: %s\n", smartstr_ptr(mystring));

/* don't forget to free you string once you're done with it */
smartstr_free(&mystring);

/* smartstr_free() sets the pointer back to NULL, so you can reuse it right away if needed */
smartstr_addf(&mystring, "Last night, I counted %d sheep.", rand());

Download

Source code is tracked and distributed through subversion:
svn co svn://svn.mateusz.fr/smartstr

smartstr is published under the terms of the MIT license. Copyright © 2025 Mateusz Viste.