Should functions of a C library always expect a string's length?

Posted by Benjamin Kloster on Programmers See other posts from Programmers or by Benjamin Kloster
Published on 2012-06-12T18:42:37Z Indexed on 2012/06/12 22:47 UTC
Read the original article Hit count: 268

Filed under:
|
|

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?

© Programmers or respective owner

Related posts about c

    Related posts about api