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;
Author by
user1705996
Updated on June 04, 2022Comments
-
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 over 11 yearsI 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 over 11 yearsI 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 over 11 years@user1705996, see ideone.com/Ju5MvX for an example. Is
nw
a class member? If so, is it definitely being initialised? -
user1705996 over 11 yearsnw 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 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 containsnw
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-three). My advice is usestd::vector
instead. -
user1705996 over 11 yearsDo 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 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.