Array out of bounds?
Author |
Message |
SJ
|
Posted: Tue Dec 30, 2008 1:03 pm Post subject: Array out of bounds? |
|
|
I've came across this today
c++: | vector <int> v;
v.push_back (5);
// version1, this doens't give an error
for (int i = 0; i+2 < v.size(); i++)
cout << v[i+2] << endl;
// version2, this goes nuts!
for (int i = 0; i < v.size()-2; i++)
cout << v[i+2] << endl; |
version 1 seem to ignore the out of bounds element, whereas version 2 print out a bunch of random numbers then freeze up. I would predict a segmentation fault for both cases, but why does the first one just (seemingly) ignore it? |
|
|
|
|
 |
Sponsor Sponsor

|
|
 |
A.J

|
Posted: Tue Dec 30, 2008 1:25 pm Post subject: Re: Array out of bounds? |
|
|
Keep in mind that you only pushed 1 element (namely '5'). So, v.size() will return 1.
Version 1 exits when i + 2 >= v.size(). But since i = 0, and v.size() = 1, it doesn't output anything (because i + 2 > v.size() ).
Although in Version 2, you want i >= v.size() - 2 for the loop to exit.....however, since i = 0 initially and v.size() - 2 = -1, the loop goes on forever (because i increases by 1, and therefore can never by less than or equal to -1)
That's why it crashes.... |
|
|
|
|
 |
SJ
|
Posted: Tue Dec 30, 2008 1:32 pm Post subject: RE:Array out of bounds? |
|
|
ahh right, thank you  |
|
|
|
|
 |
A.J

|
Posted: Tue Dec 30, 2008 1:52 pm Post subject: Re: Array out of bounds? |
|
|
no probs  |
|
|
|
|
 |
md

|
Posted: Tue Dec 30, 2008 3:33 pm Post subject: RE:Array out of bounds? |
|
|
Errm... 0 >= -1 so the second loop should exit right away... this is one of those times a debugger might help - or not waking up at 3:00 pm... |
|
|
|
|
 |
|
|