Computer Science Canada Array out of bounds? |
Author: | SJ [ Tue Dec 30, 2008 1:03 pm ] | ||
Post subject: | Array out of bounds? | ||
I've came across this today
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? |
Author: | A.J [ 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.... |
Author: | SJ [ Tue Dec 30, 2008 1:32 pm ] |
Post subject: | RE:Array out of bounds? |
ahh right, thank you ![]() |
Author: | A.J [ Tue Dec 30, 2008 1:52 pm ] |
Post subject: | Re: Array out of bounds? |
no probs ![]() |
Author: | md [ 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... |