You cannot do this.
You can determine whether a char*
value is a null pointer or not, but if it's non-null, you cannot determine whether it's a valid pointer. You certainly can't do so portably; you probably can't do it non-portably either.
For example:
char *ptr = malloc(6);
strcpy(ptr, "hello");
// now ptr points to a valid string
free(ptr);
// now ptr doesn't point to a valid string -- but there's no way to test it
If you happen to know that the pointer is valid (or is either valid or null), you still can't do it. For example:
char buf[5] = "hello"; // not a string, since there's no '\0'
char *ptr = buf; // ptr points to valid data, but it's not a string
You can scan memory starting at *ptr
looking for a '\0'
string terminator, but you can't know when to stop looking. In this case, you might look at 5 bytes of memory and not find a '\0'
-- but what if ptr
pointed to a valid string that's 1000 characters long?
And in this case, it's entirely possible that there happens to be a '\0'
byte immediately after the array, which could make it appear that ptr
points to a valid string. (Accessing that 6th byte has undefined behavior. The worst consequence of undefined behavior is that it can appear to "work", which just means it's more difficult to track down the bug.)
The only way to determine whether a pointer points to a valid string is to write your code in a way that guarantees that it does. If it doesn't, it's not a problem you can detect after it occurred.