Should functions of a C library always expect a string's length?
- by Benjamin Kloster
I'm currently working on a library written in C. Many functions of this library expect a string as char* or const char* in their arguments. I started out with those functions always expecting the string's length as a size_t so that null-termination wasn't required. However, when writing tests, this resulted in frequent use of strlen(), like so:
const char* string = "Ugh, strlen is tedious";
libFunction(string, strlen(string));
Trusting the user to pass properly terminated strings would lead to less safe, but more concise and (in my opinion) readable code:
libFunction("I hope there's a null-terminator there!");
So, what's the sensible practice here? Make the API more complicated to use, but force the user to think of their input, or document the requirement for a null-terminated string and trust the caller?