warlock's blog

By warlock, 10 years ago, In English

Recently I saw a code which was accessing the index of a vector equal to its size. The Line read

for (int i = 0; i <= nums.size(); i++) {
	max_cost[i][i] = min_cost[i][i] = nums[i];
}

The code is for the Spoj Question Pocket Money. Whole Code link.

As per my knowledge this should give segmentation fault instead the solution gets accepted. Please can someone tell me what is happening here, why it doesn't give segmentation fault!

  • Vote: I like it
  • +1
  • Vote: I do not like it

»
10 years ago, # |
  Vote: I like it +8 Vote: I do not like it

It doesn't give segmentation fault, it gives undefined behavior, which means that anything can happen. You can read more here: http://en.cppreference.com/book/undefined_behavior