Siqi Lin Siqi Lin - 1 year ago 91
C Question

Portable way to check if a char* pointer is a null-terminated string

I have a C function that takes in a char* pointer. One of the function's preconditions is that the pointer argument is a null-terminated string

void foo(char *str) {
int length = strlen(str);
// ...

isn't a pointer to a null-terminated string, then
crashes. Is there a portable way to ensure that a char* pointer really does point to a null-terminated string?

I was thinking about using
to find lowest address after
that's not readable, and if we haven't seen a null-terminator between the beginning of
and that address, then
doesn't point to a null-terminated string.

Answer Source

No, there is no portable way to do that. A null-terminated string can be arbitrarily long (up to SIZE_MAX bytes) -- and so can a char array that isn't null-terminated. A function that takes a char* argument has no way of knowing how big a chunk of valid memory it points to, if any. A check would have to traverse memory until it finds a null character, which means that if there is no null character in array, it will go past the end of it, causing undefined behavior.

That's why the standard C library functions that take string pointers as arguments have undefined behavior of the argument doesn't point to a string. (Checking for a NULL pointer would be easy enough, but that would catch only one error case at the cost of slower execution for valid arguments.)

EDIT : Responding to your question's title:

Portable way to check if a char* pointer is a null-terminated string

a pointer cannot be a string. It may or may not be a pointer to a string.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download