Hack Forums
[C] C++ Constructor/Destructor Help - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [C] C++ Constructor/Destructor Help (/showthread.php?tid=5822744)



C++ Constructor/Destructor Help - A Fresh Start - Apr 9, 2018

//constructor
{

for(int i = 0; i < MAXROWS; i++)
for(int j = 0; j < MAXCOLS; j++)
{
grid[i][j] = new Person;
}

return;
}

//destructor
{

for(int i = 0; i < MAXROWS; i++)
for(int j = 0; j < MAXCOLS; j++)
{
if(grid[i][j] != NULL)
delete grid[i][j];
}

return;
}

My destructor crashes the program, how do I make it delete the created dynamic memory without crashing, and why does it crash?


RE: C++ Constructor/Destructor Help - Annabelle Lee - Apr 9, 2018

Can't test your code myself, but I think this might do what you need?

Code
//Free each sub-array
    for(int i = 0; i < MAXROWS; ++i) {
        delete[] matrix[i];  
    }
    //Free the array of pointers
    delete[] matrix;

(Also destructor shouldn't really be checking for null or not, you should simply free the memory, since you assigned it anyways.)

Let me know if that doesn't work and please post your full class.


RE: C++ Constructor/Destructor Help - Gorzoid - Apr 9, 2018

First of all are you sure you even need pointers? Storing them by value in a STD::array or vector would make more sense.

(Apr 9, 2018 02:29 PM)Annabelle Lee Wrote:  Can't test your code myself, but I think this might do what you need?

Code
//Free each sub-array
    for(int i = 0; i < MAXROWS; ++i) {
        delete[] matrix[i];  
    }
    //Free the array of pointers
    delete[] matrix;

(Also destructor shouldn't really be checking for null or not, you should simply free the memory, since you assigned it anyways.)

Let me know if that doesn't work and please post your full class.
delete[] is only used when data is allocated using new[] iirc

OP the constructor and destructor is not enough we don't even know how grid is defined.


RE: C++ Constructor/Destructor Help - Annabelle Lee - Apr 9, 2018

(Apr 9, 2018 04:45 PM)Gorzoid Wrote:  First of all are you sure you even need pointers? Storing them by value in a STD::array or vector would make more sense.

delete[] is only used when data is allocated using new[] iirc

OP the constructor and destructor is not enough we don't even know how grid is defined.

You're right, I was simply guessing based on how I would've made it.