2

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?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
user1705996
  • 119
  • 1
  • 3
  • 12

2 Answers2

8

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));
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • I change to: delete[] nw[w]; and the error continues. I make debug and it crash. For some values ​​of w runs well, but not for others – user1705996 Dec 04 '12 at 17:29
  • @user1705996, see http://ideone.com/Ju5MvX for an example. Is `nw` a class member? If so, is it _definitely_ being initialised? – hmjd Dec 04 '12 at 17:40
  • nw is an atribute of a class: class model { public: ... int ** nw; ... } I'm printing the values and all values are 0. (One think that i don't understand is: for example: I execute it, and it crash when the value of w is 30, and if I execute it another time, crash for a diferent value of w, for example 15 or 40) – user1705996 Dec 04 '12 at 17:58
  • @user1705996, random behaviour is indicative of undefined behaviour. My guess is that `nw` is not being initialised in all versions of the constructor _or_ the object that contains `nw` is being copied and you are using the default copy constructor and default assignment operator (see http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). My advice is use `std::vector` instead. – hmjd Dec 04 '12 at 18:01
  • Do you know... whats going on if i don't implement the destructor?(when i reboot my computer the memory that i reserved its free?) – user1705996 Dec 05 '12 at 10:16
  • @user1705996, when the program exits the memory will be reclaimed by the OS. However, this is _not_ how to solve this problem. Remove chunks of your code while the error repeats and then start adding parts back in to isolate the cause. – hmjd Dec 05 '12 at 10:22
3

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

for (int w = 0; w < V; w++)
    delete[] nw[w];
delete[] nw;
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
Xymostech
  • 9,710
  • 3
  • 34
  • 44
  • I change to: delete[] nw[w]; and the error continues. I make debug and it crash. For some values ​​of w runs well, but not for others – user1705996 Dec 04 '12 at 17:32