【问题标题】:Where is my memory leak?我的内存泄漏在哪里?
【发布时间】:2012-09-22 21:23:38
【问题描述】:

所以我编写了自己的 ArrayList(也称为 C++ 中的向量)的实现,并在其中包含了几个算法。现在我的合并排序方法似乎正在泄漏内存,但我已经逐行检查了代码,跟踪分配到删除,一切似乎都很好!

我应该注意,我对 ArrayList 中的每个方法都有一个测试脚本并且我遇到了崩溃,然后我尝试删除合并排序测试,然后繁荣,不再崩溃。但有趣的是......它并不总是崩溃,它有时会工作,它会崩溃其他人。

两种方法的代码如下:

快速变量枚举:

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;
}

【问题讨论】:

  • 内存泄漏不会导致崩溃(内存不足异常除外)。那么,坠机的症状是什么?如果您发现泄漏,泄漏了多少?
  • 只需使用std::vectorstd::array,节省一些时间。
  • 你错误地认为我写这篇文章是为了功利
  • @Ethan:你到底是什么意思?
  • @EdS。他的意思是,他是为了学习目的而写作,而不是为了现实生活中的编程项目。

标签: c++ memory-management memory-leaks


【解决方案1】:

您正在访问array1 [ j ],然后再检查它是否为j &lt; size1。如果j &gt;= size1 则访问该索引处的数组是非法的。它可能并不总是崩溃,这取决于堆中事物的内存布局,但它有时会崩溃。你的支票应该是这样的:

if (((j < size1) && (array1[j] <= array2[k])) || k == size2) {
...

【讨论】:

  • 在发布此消息后我才意识到这是问题所在......我很愚蠢。谢谢!
猜你喜欢
  • 2014-04-02
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 2014-10-25
  • 1970-01-01
相关资源
最近更新 更多