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

Asked

Viewed 186 times

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 execute and display the values of others? Why the program displays values that are not part of the vector?

2 answers

2


And why wouldn’t I? In a certain way in C arrays are pointers, not exactly, but almost. Then it can access all available memory. It is the programmer’s problem not to let this happen.

I spoke in C and in fact the question has the tag. But since C++ is compatible with C, it is also valid. What a lot of people don’t understand is that C++ prefers more abstract, higher-level forms that encapsulate security checks and don’t let you do that. The array raw C which, in fact, is a pointer, should not even be used in C++, has better structures.

So vetor[4] it’s actually the same as saying *(vetor + (4 * sizeof(int)). What prevents 4000 instead of 4? Nothing. If it gives a value inside the virtual memory, it is valid. Obviously it is corrupting memory.

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

  • Very enlightening. Thank you very much, man. I’m learning c++ pq is being given in the Data Structure class on campus. Thanks for the language tips!

0

Understand that you have to be careful when indexing containers. What can happen when you try to access elements outside the limits of the variable depends on some factors. Why you are trying to access an unknown part of the computer’s memory can generate devastating consequences from generating random values to leading your program to crash. 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";
}
...
  • I got it. Thanks for the info. It was super useful bro! ♥

Browser other questions tagged

You are not signed in. Login or sign up in order to post.