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.』


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



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

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