| para1131 (6) | |
|
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
|
|
| Peter87 (3672) | |
| You have to use a loop to delete all the rows. | |
|
|
|
| EssGeEich (681) | |||||
|
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:
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:
| |||||
|
Last edited on
|
|||||