所以我寫了一個ArrayList(又名C++中的向量)的自己的實現,並且包含了幾個算法。現在我的合併排序方法似乎在泄漏內存,但我已逐行檢查代碼,將分配跟蹤到刪除,並且這一切似乎都很順利!我的內存泄漏在哪裏?
我要指出,我有一個測試腳本爲ArrayList中的每個方法和我正在崩潰,然後我試圖消除歸併測試和繁榮,沒有更多的崩潰。但有趣的是......它並不總是崩潰,它有時會起作用,並且會使其他人崩潰。
兩個方法中的代碼如下:
快速可變枚舉:
陣列=那個備份該ArrayList
尺寸數組=,保持的尺寸的軌道的int陣列。
排序=一個布爾值,表示如果列表檢查它是否j < size1
前整理
/**
* 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;
}
內存泄漏不會導致崩潰(內存不足異常除外)。那麼,墜機的症狀是什麼?如果你看到泄漏,有多少泄漏? –
只需使用'std :: vector'或'std :: array',節省一些時間。 –
你錯誤地認爲我是爲功利需求而寫這篇文章 – Ethan