Thursday, June 26, 2008

Only Subscript Elements that Are Known to Exist!

C++ Primer 4/e in 3.4. Introducing Iterators there is a warning:『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 ivec; // empty vector
cout <<> ivec2(10); // vector with 10 elements
cout << ivec[10]; //error
Chinese translation is said:『我們只能以subscript運算子([])取出實際存在的元素。這一點十分重要。例如:
vector ivec; // 空的 vector
cout <<> ivec2(10); // vector 內含 10 個元素
cout << ivec[10]; // 錯誤: ivec 的元素編號是0到9
擷取不存在的元素會造成執行期錯誤。編譯器並不保證能偵測出大部分此類錯誤。這個程式的執行結果無法確定,因為「擷取不存在元素」是一種不明確的行為,其結果視編譯器而不同,但幾乎可以確定會在執行期出現某種有趣的錯誤。
這個警告亦可套用於任何使用下標的時候,例如對string或(很快會看到)對內建的array取下標。
不幸的是,企圖以下標存取不存在的元素是極常見且致命的編程錯誤。所謂緩衝區上限溢位(buffer overflow)錯誤就是以下標存取不確定元素的結果。這種臭蟲是形成PC程式及其他應用程式安全問題的最常見原因。』
This is a good warning, especially when we from VB microsoft's series to C series using array often mistake the array start from 0 or 1 .

achi's Blog

No comments: