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

后端 未结 5 1128
感情败类
感情败类 2020-12-11 07:32

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(cha         


        
5条回答
  •  Happy的楠姐
    2020-12-11 07:46

    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.

提交回复
热议问题