[英]Where is my memory leak?
因此,我编写了自己的ArrayList实现(也就是C ++中的向量),并且包括了几种算法。 现在,我的归类排序方法似乎正在泄漏内存,但是我逐行检查了代码,跟踪分配到删除的过程,一切似乎都很好!
我应该注意,我对ArrayList中的每个方法都有一个测试脚本,并且崩溃了,然后我尝试删除mergesort测试,并且没有任何崩溃。 但是有趣的是...它不会总是崩溃,有时它会工作,而会崩溃其他人。
这两种方法的代码如下:
快速的变量枚举:
array =支持arrayList的数组
size =跟踪数组大小的int值。
sorted =一个布尔值,指示列表是否已排序
/**
* Runs merge sort on this ArrayList<T>. Interface function to the central,
* recursive, merge sort function.
*
* Runs in O(nlogn) time. However it consumes extra memory.
*/
template<class T>
void ArrayList<T>::mergeSort() {
T* temp = mergeSort(array, size);
delete [] array;
array = temp;
sorted = true;
}
/**
* Runs merge sort on the passed in array. Recursive.
*
* Runs in O(nlogn) time. However it consumes extra memory.
*
* @param array the array to sort.
* @param arraySize the size of the array that is to be sorted.
* @return the sorted array.
*/
template<class T>
T* ArrayList<T>::mergeSort(T* array, int arraySize) {
T* returnArray;
//If the array is more than one element.
if (arraySize > 1) {
int size1 = arraySize / 2;
int size2 = arraySize - size1;
T* array1;
T* array2;
//Recurse.
array1 = mergeSort(array, size1);
array2 = mergeSort(array + size1, size2);
//Allocate memory for return array.
returnArray = new T[arraySize];
//Loop through all elements in returnArray.
int i = 0, j = 0, k = 0;
while (i < arraySize) {
//Place the lesser of two elements in returnArray.
if ((array1[j] <= array2[k] && j < size1)
|| k == size2) {
returnArray[i] = array1[j];
j++;
}
else {
returnArray[i] = array2[k];
k++;
}
i++;
}
//Free the memory allocated in the recursive calls.
delete [] array1;
delete [] array2;
array1 = 0;
array2 = 0;
}
//If one element is in the passed array.
else {
//Allocate memory for new array, and assign passed value to it.
//This is done so delete can be called in the calling function.
returnArray = new T[1];
returnArray[0] = array[0];
}
return returnArray;
}
在检查是否为j < size1
之前,您正在访问array1 [ j ]
。 如果j >= size1
则在该索引处访问数组是非法的。 它可能并不总是崩溃,这取决于堆中事物的内存布局,但有时会崩溃。 您的支票应如下所示:
if (((j < size1) && (array1[j] <= array2[k])) || k == size2) {
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.