A logo showing a blue circle
Vlad-Stefan Harbuz
An illustration of yarn

pstr — a Set of Cautious and Easy-To-Use C String Functions

The default C string handling functions have a lot of problems. The biggest of these issue is the fact that they are unsafe, in the sense that they can lead to buffer overflows by copying something past the end of a string. There are safer versions, such as strlcpy, but they also have their own issues, such as implicit truncation of strings.

I needed a more reliable set of string handling functions, so I created pstr, which is a set of functions that allows you to more easily work with static C strings while preventing buffer overflows and truncation, so you don’t have to worry worrying about safety as much. pstr has two principles:

1. If a string doesn’t fit, it stops what it’s doing and tells you

Functions like strcat, strncat and strlcat try to fit as much of the source string into the destination buffer as possible. This means that you either end up with safety issues like buffer overflows, or in the best case scenario, truncated strings, which can also present problems.

strlcat(dest, "this string is way too big", 10);
// concatenated `dest` is truncated, and you have to do an extra check to detect this

pstr never overflows (hopefully), never truncates strings, and always adds the "\0" terminator. Most functions return a bool to represent whether the operation succeeded. For example, in pstr_cat, if the strings don’t fit into the buffer, it returns false without changing anything.

pstr_cat(dest, 10, "this string is way too big");
// returns false without changing `dest`

2. It’s easier to work with (than <string.h> functions)

Even when everything fits inside your buffer and you don’t have to worry about safety, doing simple things such as concatenating multiple strings can be a pain in C. pstr functions make this a little bit simpler. For example:

pstr_vcat(dest, dest_size, " Hello", " there ", name, "!", NULL);

You can read the full documentation over on the SourceHut page.

Image by irasutoya.