Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

c - 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);
    // ...
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...