c++ delete dynamic matrix

14,003

Solution 1

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

Solution 2

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

for (int w = 0; w < V; w++)
    delete[] nw[w];
delete[] nw;
Share:
14,003
user1705996
Author by

user1705996

Updated on June 04, 2022

Comments

  • user1705996
    user1705996 almost 2 years

    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?

  • user1705996
    user1705996 over 11 years
    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
    user1705996 over 11 years
    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
  • hmjd
    hmjd over 11 years
    @user1705996, see ideone.com/Ju5MvX for an example. Is nw a class member? If so, is it definitely being initialised?
  • user1705996
    user1705996 over 11 years
    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)
  • hmjd
    hmjd over 11 years
    @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 stackoverflow.com/questions/4172722/what-is-the-rule-of-thre‌​e). My advice is use std::vector instead.
  • user1705996
    user1705996 over 11 years
    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?)
  • hmjd
    hmjd over 11 years
    @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.