问题描述
我有一个接受 char* 指针的 C 函数.该函数的前提条件之一是指针参数是一个以空字符结尾的字符串
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);
// ...
}
如果 str
不是指向以空字符结尾的字符串的指针,则 strlen
崩溃.有没有一种可移植的方法来确保 char* 指针确实指向以空字符结尾的字符串?
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?
我正在考虑使用 VirtualQuery
在 str
之后找到不可读的最低地址,如果我们没有看到 str
和那个地址,那么 str
不指向以空字符结尾的字符串.
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.
推荐答案
不,没有可移植的方法来做到这一点.一个以 null 结尾的字符串可以是任意长的(最多 SIZE_MAX
个字节)——一个 char
数组也是如此,不是 null——终止.接受 char*
参数的函数无法知道它指向的有效内存块有多大(如果有的话).检查必须遍历内存直到找到空字符,这意味着如果数组中没有空字符,它将越过它的末尾,从而导致未定义的行为.
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.
这就是为什么将字符串指针作为参数的标准 C 库函数具有未定义的参数行为不指向字符串的原因.(检查 NULL
指针会很容易,但这只会捕获一个错误情况,代价是有效参数的执行速度较慢.)
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.)
回复您的问题标题:
检查 char* 指针是否为空终止字符串的可移植方法
指针不能是字符串.它可能是也可能不是指向字符串的指针.
a pointer cannot be a string. It may or may not be a pointer to a string.
这篇关于检查 char* 指针是否为空终止字符串的可移植方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!