2

I'm currently working on a string metric library, which calculates various distances between strings and reports how similar the strings are to one another. For example the Levenshtein Distance (https://en.wikipedia.org/wiki/Levenshtein_distance).

unsigned levenshtien(const char *str1, const char *str2)
{
    // check for NULL pointers
    if (str1 == NULL && str2 == NULL)
        return 0;

    if (str1 != NULL && str2 == NULL)
        return strlen(str1);

    if (str1 == NULL && str2 != NULL)
        return strlen(str2);

    // calculate length of strings
    size_t str1_len = strlen(str1);
    size_t str2_len = strlen(str2);

    // handle cases where one or both strings are empty
    if (str1_len == 0)
        return (str2_len == 0) ? 0 : 1;

    // calculate stuff here...
}

Each function in the library is passed const char * pointers. I was wondering if it was common practice to check if each of the pointers was NULL? Or should I just assume the programmer using the library would check before passing the pointers?

Rostepher
  • 201
  • 2
  • 8

2 Answers2

6

It depends on the documented interface. If the function is documented as taking two non-null strings, you might add an assertion that they're not null and get on with life with no further checks. If the function is documented to treat null pointers as if they pointed at empty strings, or something faintly similar, then that is OK and you have to do checking and adjusting as appropriate. There's nothing wrong with checking and handling invalid parameters as your code does even if the function is documented as taking non-null pointers to valid null-terminated strings, but it bulks up your code for minimal benefit to those who can read your documentation.

The standard C library functions (such as strcmp()) simply require the arguments to be valid strings. You invoke undefined behaviour if you pass a null pointer to it. It can crash, or not, at the whim of the implementer.

For your function, it seems likely to be reasonable that users would only supply valid pointers; an assertion to keep them honest is good, and that's all that's needed.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
0

Always check for potential error cases and handle them appropriately (throw exception, return error code, do nothing, etc). Failing to a null pointer exception isn't a good thing.

CDahn
  • 1,795
  • 12
  • 23