Search code examples
c++memory-leaksstdlist

Memory leak in using a list of lists


I had some code thrown at me to 'productionize.' I ran a memory leak checker and it calls out the following line within the 'for' loop below as a memory leak.

someStruct->arrayMap = new std::list<BasisIndex>*[someStruct->mapSizeX];
for(int i=0; i<someStruct->mapSizeX; i++){  
    someStruct->arrayMap[i] = new std::list<BasisIndex>[someStruct->mapSizeY];
}

Here is how the array map is declared:

struct SomeStruct{
    int mapSizeX;
    int mapSizeY;
    std::list<BasisIndex>** arrayMap;
};

Here are a couple usages of it:

someStruct->arrayMap[xVal][yVal].push_back(tempIndex);

for(it = someStruct->arrayMap[xVal][yVal].begin(); it != someStruct->arrayMap[xVal][yVal].end(); it++){
    ...
}

The memory leak checker dumped for 5 minutes before I killed it. Then I added the following bit of code in a cleanup routine but it still dumps out 150 warnings all pointing to the line of code within the for loop at the top.

for(int x=0; x<someStruct->mapSizeX; x++){
    for(int y=0; y<someStruct->mapSizeY; y++){
        someStruct->arrayMap[x][y].clear();
        someStruct->arrayMap[x][y].~list();
    }
}

std::list<BasisIndex> ** temp = someStruct->arrayMap;
delete temp;

How do I completely delete the memory associated with this array map?


Solution

  • Deallocate the objects in the reverse order that you allocated them.

    Allocation:

    someStruct->arrayMap = new std::list<BasisIndex>*[someStruct->mapSizeX];
    for(int i=0; i<someStruct->mapSizeX; i++){  
        someStruct->arrayMap[i] = new std::list<BasisIndex>[someStruct->mapSizeY];
    }
    

    Deallocation:

    for (int i=0; i<someStruct->mapSizeX; i++){
        delete[] someStruct->arrayMap[i];
    }
    delete[] someStruct->arrayMap;