Reputation: 142
I've been having bad luck with dynamic pointers when I want to close it. why the application wrote to memory after end of heap buffer? how can I close my array?
int main()
{
.
.
int **W;
W = new int* [n];
for (int i=1; i <= n; i++)
W[i] = new int[n];
.
.
.
ast(n,W);
for(int i = 1; i <=n ; i++)
{
delete W[i];
}
delete W;
getch();
}
void ast (int n,int **W)
{
int **D;
D = new int* [n];
for (int i=0; i < n; i++)
D[i] = new int[n];
D=W;
for (int k=1;k<=n;k++)
for (int i=1;i<=n;i++)
for (int j=1;j<=n;j++)
D[i][j]=min(D[i][j],D[i][k]+D[k][j]);
.
.
for(int i = 1; i <=n ; i++)
{
delete D[i];
}
delete D;
}
Upvotes: 0
Views: 71
Reputation: 311166
The valid range of indices of an array with N
elements is [0, N-1]
.
Thus instead of for example this loop
for (int i=1; i <= n; i++)
^^^^ ^^^^^^
you have to write
for ( int i = 0; i < n; i++ )
As you used operator new []
you have to use operator delete []
So instead of
for(int i = 1; i <=n ; i++)
{
delete W[i];
}
and
delete W;
you have to write
for ( int i = 0; i < n; i++ )
{
delete [] W[i];
}
and
delete []W;
Function ast
does not make sense because apart from other errors it has a memory leak. At first you allocate memory and assign its address to pointer D
and then you overwrite this value of the pointer
void ast (int n,int **W)
{
int **D;
D = new int* [n];
for (int i=0; i < n; i++)
D[i] = new int[n];
D=W; // <== ???
Upvotes: 2