简体   繁体   中英

pointer to pointer dynamic array in C++

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

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; // <== ???

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM