简体   繁体   中英

Confused about deleting dynamic memory allocated to array of struct

I'm having a memory leak issue and it's related to an array of structs inside a class (not sure if it matters that they're in a class). When I call delete on the struct, the memory is not cleared. When I use the exact same process with int and dbl it works fine and frees the memory as it should.

I've created very simple examples and they work correctly so it's related to something else in the code but I'm not sure what that could be. I never get any errors and the code executes correctly. However, the allocation / deallocation occurs in a loop so the memory usage continually rises.

In other words, here's a summary of the problem:

struct myBogusStruct {
    int bogusInt1, bogusInt2;
};

class myBogusClass {
    public:
       myBogusStruct *bogusStruct;
};

void main(void) {

    int i, arraySize;
    double *bogusDbl;
    myBogusClass bogusClass;

    // arraySize is read in from an input file

    for(i=0;i<100;i++) {
        bogusDbl = new double[arraySize];
        bogusClass.bogusStruct = new myBogusStruct[arraySize];

        // bunch of other code

        delete [] bogusDbl; // this frees memory
        delete [] bogusClass.bogusStruct; // this does not free memory
    }
 }

When I remove the bunch of other code, both delete lines work correctly. When it's there, though, the second delete line does nothing. Again, I never get any errors from the code, just memory leaks. Also, if I replace arraySize with a fixed number like 5000 then both delete lines works correctly.

I'm not really sure where to start looking - what could possibly cause the delete line not to work?

There is no reason at all for you to either allocate or delete myBogusDbl inside the for loop, because arraySize never changes inside the loop.

Same goes for myBogusClass.myBogusStruct . No reason to allocate/delete it at all inside the loop:

myBogusDbl = new double[arraySize];
myBogusClass.myBogusStruct = new bogusStruct[arraySize];

for (i = 0; i < 100; i++) {
    // bunch of other code
}

delete[] myBogusDbl;
delete[] myBogusClass.myBogusStruct;

You should also consider using std::vector instead of using raw memory allocation.

Now to the possible reason of why the second delete in the original code doesn't do anything: deleting a NULL pointer does, by definition, nothing. It's a no-op. So for debugging purposes, try introducing a test before deleting it to see if it's NULL and if yes abort(). (I'd use a debugger instead though, as it's much quicker to set up a watch expression there compared to writing debug code.)

In general though, we need to see that "bunch of other code".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM