Tanner - 1 year ago 139

C++ Question

I've looked at similar questions (such as this, this, and this), but I still can't figure this out. On a few test cases, I'm getting the error and can't make sense of it. The error I'm getting is:

`free(): invalid next size (fast)`

My code uses the Robot Coin Collection algorithm. My implementation of it is below:

`int collectTens( vector< vector<int> > grid ) {`

vector<vector<int>> result(grid.size(), vector<int>(grid.size(), 0));

int rows = grid.size();

int cols = grid[0].size();

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

if (grid[i][j] % 10 != 0) {

grid[i][j] = 0;

}

}

}

result[0][0] = grid[0][0];

for (int k = 1; k < cols; k++) {

result[0][k] = result[0][k - 1] + grid[0][k];

}

for (int i = 1; i < rows; i++) {

result[i][0] = result[i - 1][0] + grid[i][0];

for (int j = 1; j < cols; j++) {

result[i][j] = max(result[i - 1][j], result[i][j - 1]) + grid[i][j];

}

}

cerr << result[rows - 1][cols - 1] << endl;

return result[rows - 1][cols - 1];

}

In the test cases that the error occurs, the result can be outputted using stderr but will not be able to return anything due to the error. Which is the part that doesn't really make sense to me, because it is the same position in the 2D vector.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

The line

```
vector<vector<int>> result(grid.size(), vector<int>(grid.size(), 0));
```

creates square grid, not a rectangular grid. You probably meant to use:

```
vector<vector<int>> result(grid.size(), vector<int>(grid[0].size(), 0));
^^^^
```

I suggest using:

```
int rows = grid.size();
int cols = grid[0].size();
vector<vector<int>> result(rows, vector<int>(cols, 0));
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**