Search code examples
c++pascals-triangle

How to fix an address issue


I'm trying to solve a Pascal's Triangle problem on Leetcode. I get this error when I run the code.

AddressSanitizer: heap-buffer-overflow on address 0x602000000014 at pc 0x000000407875 bp 0x7ffe13bd9300 WRITE of size 4 at 0x602000000014 thread T0.

How should I fix it?

class Solution {
public:
    vector<vector<int>> generate(int numRows) {


        vector<vector<int>> tri(numRows);

        vector<int> row;
        row.push_back(1);
        tri.push_back(row);
        row.clear();

        for (int i = 1; i < numRows; i++) {
            row[0]=1;
            row[i]=1;
            for (int j = 1; j < i; j++) {

                    row[j] = tri[i-1][j] + tri[i-1][j-1]; 

            }
            tri[i] = row;
            row.clear();
        }
        return tri;

    }
};

Solution

  • When you call row.clear(), that wipes the row and sets the length to 0. As a result, when you try accessing row[0], row[i], etc, you're accessing memory that you shouldn't be touching.