I am trying to allocate two-D array at runtime. Size of the array is N*N where N is input by the user.
In the end I am deleting the allocated memory. But I am getting Segmentation Fault.
I know that Segmentation fault occurs when I try to access memory not allocated by me. Please Help Code is as follows:
#include<iostream>
using namespace std;
#include <stdio.h>
int main ()
{
int t,n;
int **judge;
int **result;
int i,j,l;
int high;
float count;
int item;
cin>>t;
while(t-->0)
{
cin>>n;
judge=new int*[n];result=new int*[n];
for(i=0;i<n;i++)
{
judge[i]=new int[n];
result[i]=new int[n];
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cin>>judge[i][j];
}
}
count=0;
result[0][0]=0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
item=0;
if(j>0&&i>0)
{
if(item<result[i][j-1])
item=result[i][j-1];
else if(item<result[i-1][j])
item=result[i-1][j];
}
else if(i==0)
{
if(item<result[i][j-1])
item=result[i][j-1];
}
else if(j==0)
{
if(item<result[i-1][j])
item=result[i-1][j];
}
result[i][j]=judge[i][j]+item;
}
}
if(result[n-1][n-1]<0.0)
cout<<"Bad Judges"<<endl;
else
{
count=(result[n-1][n-1]/(float)n);
cout<<count<<endl;
}
for( i = 0 ; i < n ; ++i)
{
delete[] result[i] ;
}
delete[] result;
for(i = 0 ; i < n ; ++i)
{
delete[] judge[i] ;
}
delete[] judge;
/* for(i=0;i<n;i++)
{
delete[] judge[i];
delete[] result[i];
}*/
// delete[] judge;
//delete[] result;
}
}
You loop
judgetilln+2and you do not allocate that much.In those three lines:
By the way this is not the only time you access memory you have not allocated:
Here
iandjmight reach up ton, whilst your allocation allows for values up ton -1.