`

strcmp和strncasecmp需要担心比较溢出的问题吗?

阅读更多
请看一段有冗余的代码: ... int ifBQ = 0; while (*src != 0) { if (*(src+1) == '\0') // 冗余部分 break; if (strncasecmp(*content, "B?", 2) == 0) { ifBQ = 1; break; } if (strncasecmp(*content, "Q?", 2) == 0) { ifBQ = 2; break; } src++; } ... 作者的思路是以为strncasecmp不能处理如strncasecmp("h", "?Q", 2)的代码。 其实在strncasecmp的手册中,我们可以看到: ... not more than n bytes from the string pointed to by s1 to ... 可见这个比较函数中第三个参数,是让两个字符处比较不超过n个字符,而并非一定要比较那么多个字符。没有内存访问越界的问题。 为了验证这个结论,我们可以做如下测试: [dinghuaneng@176 test]$ cat test.c #include <stdio.h> #include <string.h> int main(void) { char *str1 = "h"; if (strncasecmp(str1, "hello", strlen("hello")) == 0) printf("find hello!\n"); else printf("None\n"); return 0; } 运行结果: [test@pctest]$ ./test None</string.h></stdio.h>
0
6
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics