Clearing array of objects

Hi everyone,

I'm having the following issue. I have made a GUI in Qt but it is crashing and I'm not sure of the reason. I've tried to debugged it to no success. My program creates a hash table of objects but then I try to clear it when I open another file. When I tried to debug it, the program was skipping this function and (I know it's going to sound weird, when I commented out the function call, the program seemed to try to execute the comment. This what I have. Please if this is wrong or can be improved, would you mind to post it ? Any help is really appreciated

1
2
3
4
5
6
7
8
9
10
11
12

void Directory::DeleteTable(){

        for(int i=0; i < TABLESIZE; i++)
        {
            if(table[i] != NULL)
            {
                delete table[i];
            }
        }
    }
            
Last edited on
When you first created the table, did you make sure every table[i] was NULL?
If you don't make them NULL, you'll try and delete garbage later on.

When you performed any incremental deletes, did you remember to also set the corresponding table[i] to NULL?
If you don't make them NULL, you're just double-deleting things.

The whole problem goes away if you use some kind of smart pointer, or better yet, some pre-existing container like std::vector.

DIY memory management is a PITA to fix when it inevitably goes wrong.
PITA: pain in the (Sulu voice, "oh my")

BTW, I'm not answering this guy anymore. He totally ignored my last answer. What a d-head. ("oh my").
1
2
3
4
            if(table[i] != NULL)
            {
                delete table[i];
            }

This is a fake safety check, only meant to fool yourself into the illusion of safety. delete on a nullptr is a no-op.
Last edited on
right so it needs to be

{
delete table[i];
table[i] = 0; //not required, but self defense
}
Last edited on
Topic archived. No new replies allowed.