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);
// ...
}
If str
isn't a pointer to a null-terminated string, then strlen
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 VirtualQuery
to find lowest address after str
that's not readable, and if we haven't seen a null-terminator between the beginning of str
and that address, then str
doesn't point to a null-terminated string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With