user1705996
user1705996

Reputation: 139

c++ delete dynamic matrix

I have this code to allocate and initialize:

nw = new int*[V];

for (w = 0; w < V; w++) {

nw[w] = new int[K];

for (k = 0; k < K; k++) 

  nw[w][k] = 0;
}

and this to free memory:

if (nw) {
 for (int w = 0; w < V; w++) {  
  if (nw[w]) 
delete nw[w];      
}

The program compile and runs, but, when its try to deallocate memory, fails. The program not always fails at the same value of w.

Any ideas?

Upvotes: 2

Views: 16701

Answers (2)

hmjd
hmjd

Reputation: 121971

When new[] use delete[], so change to:

delete[] nw[w];

and remember to delete[] nw;.

Note that the individual assignment of 0 to each int in the array can be replaced with:

nw[w] = new int[K](); // This value initializes the array, in this
                //^^     case sets all values to zero.

You can avoid explicitly handling dynamic allocation with std::vector<std::vector<int>>:

std::vector<std::vector<int>> nw(V, std::vector<int>(K));

Upvotes: 8

Xymostech
Xymostech

Reputation: 9850

I think you meant to use delete[], not delete:

for (int w = 0; w < V; w++)
    delete[] nw[w];
delete[] nw;

Upvotes: 3

Related Questions