Hasan0540's blog

By Hasan0540, 9 years ago, In English

Can anyone explain why does the first code get Runtime Error?

RTE: http://ideone.com/7UNoVJ

OK: http://ideone.com/fOWbj3

Thanks!

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

»
9 years ago, # |
  Vote: I like it 0 Vote: I do not like it

I tried debugging it and it seems to have something to do with the order of the equalization, and the vector usage. You cannot use [] operators when the size of vector is 0. So when we use in the first call reg[] we are trying to access an vector of size 0, which causes an error.

The problem ceases when we resize the vector to size 1. Here.

Or in your second example when we resize the vector using the function, before trying to access the vector itself.

  • »
    »
    9 years ago, # ^ |
      Vote: I like it +4 Vote: I do not like it

    Thank you for your reply!

    But in this code I'm not using [] operator with an empty vector, and still have a runtime error?

    • »
      »
      »
      9 years ago, # ^ |
        Vote: I like it +8 Vote: I do not like it

      The thing is: you use invalid memory when assigning to reg[x], because the function, which result is assigned to reg[x], does change the vector (and, possibly, it's allocation). See this comment for detailed explanation.

»
9 years ago, # |
  Vote: I like it +13 Vote: I do not like it

I suspect that function getRegIndex might cause vector relocation in memory, so reg[getRegIndex(1,reg)] won't be part of your vector anymore.

  • »
    »
    9 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    I think you are right, here I increase the capacity before calling the function and there is no problem.

    Thank you!