c++ - Accessing an array out of bounds gives no error, why? -
i assigning values in c++ programme out of bounds this:
#include <iostream> using namespace std; int main() { int array[2]; array[0] = 1; array[1] = 2; array[3] = 3; array[4] = 4; cout << array[3] << endl; cout << array[4] << endl; homecoming 0; }
the programme prints 3
, 4
. should not possible. using g++ 4.3.3
here compile , run command
$ g++ -w -wall errorrange.cpp -o errorrange $ ./errorrange 3 4
only when assigning array[3000]=3000
give me segmentation fault.
if gcc doesnt check array bounds, how can sure if programme correct, can lead serious issues later?
i replaced above code with
vector<int> vint(2); vint[0] = 0; vint[1] = 1; vint[2] = 2; vint[5] = 5; cout << vint[2] << endl; cout << vint[5] << endl;
and 1 produces no error.
solution: utilize std containers when possible instead of raw arrays, , utilize .at()
instead of []
correct, defined behavior.
welcome every c/c++ programmers bestest friend: undefined behavior.
there lot not specified language standard, variety of reasons. 1 of them.
in general, whenever encounter undefined behavior, anything might happen. application may crash, may freeze, may eject cd-rom drive or create demons come out of nose. may format harddrive or email porn grandmother.
it may even, if unlucky, appear work correctly.
the language says should happen if access elements within bounds of array. left undefined happens if go out of bounds. might seem work today, on compiler, not legal c or c++, , there no guarantee it'll still work next time run program. or hasn't overwritten essential info now, , haven't encountered problems that going cause yet.
as why there no bounds checking, there couple aspects answer:
an array leftover c. c arrays primitive can get. sequence of elements contiguous addresses. there no bounds checking because exposing raw memory. implementing robust bounds-checking mechanism have been impossible in c. in c++, bounds-checking possible on class types. array still plain old c-compatible one. not class. further, c++ built on rule makes bounds-checking non-ideal. c++ guiding principle "you don't pay don't use". if code correct, don't need bounds-checking, , shouldn't forced pay overhead of runtime bounds-checking. so c++ offersstd::vector
class template, allows both. operator[]
designed efficient. language standard not require performs bounds checking (although not forbid either). vector has at()
fellow member function is guaranteed perform bounds-checking. in c++, best of both worlds if utilize vector. array-like performance without bounds-checking, and ability utilize bounds-checked access when want it. c++ arrays
No comments:
Post a Comment