pascal triangle

Jan 4, 2020 at 5:31am
Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h> 
#include <limits.h> 
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

using namespace std;

  class Solution {
public:
    vector<vector<int>> generate(int numRows) {
       vector<vector<int>>k(numRows,vector<int>(numRows,0));
        
        for(int i=0;i<numRows;i++){
             k[i][0]=1;
            for(int j=0;j<=i;j++){
               if(i==j)
                k[i][j]=1;
                else
                {
                  k[i][j]=k[i-1][j-1]+k[i-1][j];
                }
                
                
            }
            
    }
        return k;
    }
    
};


i'm learning recursive and try this problem of leet code,
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it.

Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

i compile my code but there is error, it says runtime error
=================================================================
==29==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60300000003c at pc 0x000000406740 bp 0x7ffe037da8b0 sp 0x7ffe037da8a8
READ of size 4 at 0x60300000003c thread T0

https://leetcode.com/explore/featured/card/recursion-i/251/scenario-i-recurrence-relation/1659/

i debug my code in my computer, and it produce correct result ? what is the cause of error?
Last edited on Jan 4, 2020 at 5:31am
Jan 4, 2020 at 5:36am
Follow through what happens on the second iteration, i = 0 and j = 1.
i != j, so line 22 is hit.
You attempt to access k[-1][0], which goes out of bounds of your array.

"buffer overflow" means you're attempting to write to data beyond what you're supposed to write to.
Last edited on Jan 4, 2020 at 5:38am
Jan 4, 2020 at 10:04am
@Ganado thankyou for the help!!!
Topic archived. No new replies allowed.