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;
}
```