0

I have a vector of vector built in the following way:

std::vector<std::vector<int>> symbols;

I want to insert some int in the structure. To do this, I want to check that the position in which the int will be inserted is legal. I'm trying to make the vector growing up in a dynamic way. For this reason, I wrote the following code:

void checkIndex(unsigned int i0, unsigned int i1) {
int mult_fac=2;
if(i0>=symbols.capacity()-1){
    symbols.reserve((i0+1)*mult_fac);

}
if(i1>=symbols[i0].capacity()-1){
    symbols[i0].reserve((i1 + 1)*mult_fac);
}

}

To verify that all of this works, I wrote a main:

int main() {

for(;;){
    int i=rand()%1000;
    int j=rand()%1000;
    checkIndex(i,j);
}
return 0;}

But, the output shows a bad memory access:

"Process finished with exit code -1073741819 (0xC0000005)"

I'm using Windows 10. I can't understand how to fix it! Thanks for helping me.

  • 1
    `reserve` only allocates space, it doesn't create objects in the vector. Therefore you cannot access `symbols[i0]` if there is no object at that index – UnholySheep Apr 16 '20 at 17:55

1 Answers1

0

The obvious problems are that capacity() doesn't tell you the size of the vector, you need size() instead and that reserve() doesn't change the size of the vector, you need resize() instead.

Finally your tests are too pessimistic, after changing caapcity for size you could just have

if (i0 >= symbols.size()) {

and

if (i1 >= symbols[i0].size()) {

You don't need the -1 in there, an index is invalid if it is >= to the size.

john
  • 85,011
  • 4
  • 57
  • 81
  • What did you read there that made you not use it? If you want to resize your vector it's the obvious thing to use. – john Apr 16 '20 at 18:44
  • I didn't use the resize, because I've read on the cpp reference that: If the current size is greater than count, where count is the argument of the resize method, the container is reduced to its first count elements: [link] https://en.cppreference.com/w/cpp/container/vector/resize – Martina_bxxu Apr 16 '20 at 18:44
  • @Martina_bxxu But the current size cannot be greater than the count `if (i0 >= symbols.size()) {` prevents that. The vector is only growing. – john Apr 16 '20 at 18:51