Only Subscript Elements that Are Known to Exist!

C++ Primer 4/e 在Iterators這裡有一個警告:『It is crucially important to understand that we may use the subscript operator, (the [] operator), to fetch only elements that actually exist. For example,

     vector<int> ivec;      // empty vector
     cout << ivec[0];       // Error: ivec has no elements!

     vector<int> ivec2(10); // vector with 10 elements
     cout << ivec[10];      // Error: ivec has elements 0...9

 

Attempting to fetch an element that doesn’t exist is a run-time error. As with most such errors, there is no assurance that the implementation will detect it. The result of executing the program is uncertain. The effect of fetching a nonexisting element is undefinedwhat happens will vary by implementation, but the program will almost surely fail in some interesting way at run time.

This caution applies any time we use a subscript, such as when subscripting a string and, as we’ll see shortly, when subscripting a built-in array.

Attempting to subscript elements that do not exist is, unfortunately, an extremely common and pernicious programming error. So-called “buffer overflow” errors are the result of subscripting elements that don’t exist. Such bugs are the most common cause of security problems in PC and other applications.』

中文版的是這樣說:『我們只能以subscript運算子([])取出實際存在的元素。這一點十分重要。例如:

    vector<int> ivec;         // 空的 vector
    cout << ivec[0];           // 錯誤: ivec 裡沒有元素
  
  vector<int> ivec2(10); // vector 內含 10 個元素
     cout << ivec[10];        // 錯誤: ivec 的元素編號是0到9

擷取不存在的元素會造成執行期錯誤。編譯器並不保證能偵測出大部分此類錯誤。這個程式的執行結果無法確定,因為「擷取不存在元素」是一種不明確的行為,其結果視編譯器而不同,但幾乎可以確定會在執行期出現某種有趣的錯誤。

這個警告亦可套用於任何使用下標的時候,例如對string或(很快會看到)對內建的array取下標。

不幸的是,企圖以下標存取不存在的元素是極常見且致命的編程錯誤。所謂緩衝區上限溢位(buffer overflow)錯誤就是以下標存取不確定元素的結果。這種臭蟲是形成PC程式及其他應用程式安全問題的最常見原因。』

這個是很有用的警告,特別是從VB 微軟系列到C 系列的陣列使用常會弄錯元素是0開始或是1開始。

感謝你看到這裡,很快就可以離開了,但最好的獎勵行動就是按一下幫我分享或留言,感恩喔~

點我分享到Facebook

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *