0

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;
}
5
  • W indices are from 0 to n-1 instead of 1 to n. Commented Jun 22, 2015 at 9:28
  • Can you explain more? Commented Jun 22, 2015 at 9:30
  • 1
    You should loop from 0 to n-1 instead of 1 to n. Better still, use std::vector. Commented Jun 22, 2015 at 9:32
  • I start array index with 0 to <n but it already is false! Commented Jun 22, 2015 at 9:36
  • 2
    @illusionist_yahya You're working with "dynamic arrays" and you were not aware that (even simple) arrays start at index 0? Commented Jun 22, 2015 at 9:40

1 Answer 1

2

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; // <== ???
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.