Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C 

C++ Constructor/Destructor Help

//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?
Signature Space available for free, PM me if you'd like to use it.
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.
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.
(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.


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C] by SмℯґƒMay 1, 2020 09:00 PM 2 150 May 1, 2020 09:00 PM
Last Post: 0xDEAD10CC
[C] by zNinjaDec 15, 2017 12:21 PM 5 247 Dec 15, 2017 12:21 PM
Last Post: 0xDEAD10CC
[.NET] by SirNoobHackSep 25, 2016 03:21 PM 4 194 Sep 25, 2016 03:21 PM
Last Post: idb.