
上QQ阅读APP看书,第一时间看更新
2.2.2 差一错误
空字符结尾的字符串的另一个常见问题是差一错误(off-by-one error)。差一错误与无界字符串复制有相似之处,即都涉及对数组的越界写问题。下列程序在微软Visual C++2010的/W4警告级别上完全可以编译和链接,并且在Windows 7上运行时也不报错,但它包含了几个差一错误。你能找出这个程序中所有的差一错误吗?
01 #include <string.h> 02 #include <stdio.h> 03 #include <stdlib.h> 04 05 int main(void) { 06 char s1[] = "012345678"; 07 char s2[] = "0123456789"; 08 char *dest; 09 int i; 10 11 strcpy_s(s1, sizeof(s2), s2); 12 dest = (char *)malloc(strlen(s1)); 13 for (i=1; i <= 11; i++) { 14 dest[i] = s1[i]; 15 } 16 dest[i] = '\0'; 17 printf("dest = %s", dest); 18 /* ... */; 19 }
这些错误中,很多都是新手易犯的错误,但经验丰富的程序员也可能犯同样的错误,很容易开发出并部署类似于这个例子的程序,因为它在大多数系统上都可以顺利通过编译并且运行时也不报错。