Segmentation fault while returning a 2d vector in C++

138 views Asked by At
vector<vector<int> > Solution::prettyPrint(int A) 
   {
       vector<vector<int>>res(2*A-1, std::vector<int>(2*A-1));
       int flag=A;

       int i, k=0,l=0;
       int m=2*A-1, n=2*A-1;
       while(k<=m && l<=n)
          {
               for(i=l; i<2*A-1; i++)
                   res[k][i]=flag;//1st row
               k++;

               for(i=k; i<2*A-1; i++)
                   res[i][n]=flag;//last column
               n--;

               for(i=n; i>l; i--)
                   res[m][i]=flag;//last row
               m--;

               for(i=m; i>k; i--)
                  res[i][l]=flag;//1st column
               l++;

               flag--;


           }
            return res;
        }

why does it give segmentation fault error as i have allocated memory for the complete 2d matrix which will be [2A-1][2A-1].

if A=3 output must be like 3 3 3 3 3 \n 3 2 2 2 3 \n 3 2 1 2 3 \n 3 2 2 2 3 \n 3 3 3 3 3 \n

2

There are 2 answers

0
Federico On

Here is your error:

while(k<=m && l<=n)

You should use:

while(k<m && l<n)

Because vector indexes starts from 0 and not from 1.

0
gsamaras On

You go out of bounds, since indexing starts from 0 to 2*A-1. Since int m=2*A-1, n=2*A-1; you need to change this:

while(k<=m && l<=n)

to this:

while(k < m && l < n)