template ,dynamic 2d array, memory leak

I have a class that use these template to create and delete dynamic array and return 2d array pointer to caller.I used valgrind to check memory leak it point to dynamicArray[i] = new T[nCols]; and the point wich is called from
as a leak memory point with about 1M of leak memory in 9 iteration. and
as the number iterating or create and deleting array will increase the amount of leak will increase too..


template<typename T>
T **AllocateDynamicArray(uint nRows, uint nCols) {
T **dynamicArray;

dynamicArray = new T*[nRows];
for (uint i = 0; i < nRows; i++)
dynamicArray[i] = new T[nCols]; <<==============memory leak

return dynamicArray;
}

template<typename T>
void FreeDynamicArray(T** dArray) {
delete[] *dArray;
delete[] dArray;
}

Do you think that there is any thing wrong in creating and deleting dynamic 2d array or not.and how can I
fix this memory leak?

Thank you in advance.
ecplusplus
Last edited on
You have to use a loop to delete all the rows.
I don't see anything wrong, that's a "AllocateDynamicArray" function. It probably finds a Memory Leak, as it does not know you will call FreeDynamicArray by yourself.
I don't think there is anything wrong, as long as you call FreeDynamicArray in the RIGHT way (that isn't the right way to delete a Dynamic Array).
You should delete it like:
1
2
3
4
5
6
7
8
template<typename T>
void FreeDynamicArray(T ** dArray, unsigned long Size) {
    for(unsigned long i = 0; i < Size; i++)
    {
         delete dArray[i];
    }
    delete dArray;
};

This deletes every item, when you deleted only the first item.
Maybe yours could work, but i think not at all.
EDIT: You may want to create a struct for such things, like:
1
2
3
4
5
template<typename T>
struct DynamicAlloc {
    T ** Pointer;
    unsigned long Size;
};
Last edited on
Topic archived. No new replies allowed.