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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…