- C和C++安全編碼(原書第2版)
- (美)Robert C.Seacord
- 286字
- 2020-10-30 17:56:38
2.2.2 差一錯誤
空字符結(jié)尾的字符串的另一個常見問題是差一錯誤(off-by-one error)。差一錯誤與無界字符串復(fù)制有相似之處,即都涉及對數(shù)組的越界寫問題。下列程序在微軟Visual C++2010的/W4警告級別上完全可以編譯和鏈接,并且在Windows 7上運(yùn)行時也不報錯,但它包含了幾個差一錯誤。你能找出這個程序中所有的差一錯誤嗎?
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 }
這些錯誤中,很多都是新手易犯的錯誤,但經(jīng)驗(yàn)豐富的程序員也可能犯同樣的錯誤,很容易開發(fā)出并部署類似于這個例子的程序,因?yàn)樗诖蠖鄶?shù)系統(tǒng)上都可以順利通過編譯并且運(yùn)行時也不報錯。
推薦閱讀
- Design Principles for Process:driven Architectures Using Oracle BPM and SOA Suite 12c
- Android應(yīng)用程序開發(fā)與典型案例
- Azure IoT Development Cookbook
- Hands-On Data Structures and Algorithms with JavaScript
- C語言程序設(shè)計案例式教程
- C程序設(shè)計案例教程
- HTML5+CSS3網(wǎng)頁設(shè)計
- Linux Device Drivers Development
- Python圖形化編程(微課版)
- JSP程序設(shè)計實(shí)例教程(第2版)
- Mastering Docker
- 自學(xué)Python:編程基礎(chǔ)、科學(xué)計算及數(shù)據(jù)分析(第2版)
- Android嵌入式系統(tǒng)程序開發(fā)(基于Cortex-A8)
- Python高性能編程(第2版)
- H5頁面設(shè)計與制作(全彩慕課版·第2版)