Why do you accept values beyond the size of the vector?

2
 INT vetor[3];
 vetor[0] = 110;
 vetor[1] = 12;
 vetor[2] = 30;
 vetor[3] = 13;
 vetor[4] = 1;

  Cout <<   vetor[0];
  Cout <<   vetor[1];
  Cout <<   vetor[2];
  Cout <<   vetor[3];
  Cout <<   vetor[4];

In short: I said that my vector has size 3. But I gave 5 values to my vector. The question is, do you know why it will perform and show the values of others? Why does the program display values that are not part of the vector?

    
asked by anonymous 01.08.2017 / 04:19

2 answers

2

And why would not it? In a way in C arrays are pointers , not exactly, but almost. Then it can access all available memory. It is the developer's problem not to let this happen.

I spoke in C and in fact the question has the tag . But since C ++ is C-compliant, that's fine too. What most people do not understand is that C ++ prefers more abstract, more high-level forms that encapsulate security checks and do not let it do that. The raw array of C which, in fact, is a pointer, should not even be used in C ++, has better structures .

So vetor[4] is actually the same as *(vetor + (4 * sizeof(int)) . What stops being 4000 in place of 4? Anything. If it gives a value within virtual memory, it is valid. Obviously it is corrupting memory.

If you want something more secure, just use the secure parts of C ++, and pass away from C, or go to a language that always gives security, like Java or C #, just to stay in the mainstream which are closest to C ++. C and C ++ is for those who want great powers and can have great responsibilities.

    
01.08.2017 / 05:49
0

Understand that you have to be careful when indexing containers. What can happen when you try to access elements outside the bounds of the variable depends on a few factors. Why you are trying to access an unknown part of your computer's memory can lead to devastating consequences since it generates random values until your program crashes. When working with variable limits it is recommended to create a constant variable to check if you are trying to access something illegal or not.

...
const int MAX_INDEX = 4;
if (i < MAX_INDEX + 1){

    vector[i];

}
else{
    cout << "Já avisei que vai dar mer** isso ae";
}
...
    
01.08.2017 / 18:50