J. Doe - 7 months ago 34

C++ Question

I am using a vector of vector in my A3 code. I sort the vector of vector's at insertion. I store my keys in the 0th index of each sub vector.

In my size method, I am trying to use the direct call for checking the size. The code below outlines my attempt. However, I get a segmentation fault on execution. Can anyone help me understand the reason for the same?

`vector<vector<int>> pairs; //sorted in the insert method`

int size(int key) const {

if( pairs[key].size() == 0 ) { return -1; }

else { return pairs[key].size() - 1; }

}

I have implemented the same successfully previously, however, it was a very inefficient solution using linear search. Here is the code for the same:

`int size(int key) const`

{

for( int i=0; i<pairs.size(); i++)

{

if( pairs[i][0] == key )

{

return pairs[i].size() - 1;

}

}

return -1;

}

Answer

This code is not enough to tell you what is happening, we can only make a guess.

I would say that your leak comes from the method data: you create a copy of the data and then return a pointer to this copy. It would be better to return an unique_ptr, so the memory is released automatically.

If you cannot change the definition of the method, then you could change the body of the method by this one:

```
int length = size(key);
if( length == -1 )
return nullptr;
for( int i=0; i<pairs.size(); i++)
{
if( pairs[i][0] == key )
{
return &pairs[i][1];
}
}
return nullptr;
```

Source (Stackoverflow)