代码之家  ›  专栏  ›  技术社区  ›  Trace Langfels

指针、动态数组和内存泄漏

  •  -2
  • Trace Langfels  · 技术社区  · 7 年前

    我的完整代码链接在底部。

    我遇到的第一个问题是,在第一次需要增加大小后,动态分配的数组变得混乱。相关代码如下。

        while (counter <= arraySize)
        {
            cout <<"Please enter an integer number. Use 999999 (six 9's) to stop\n";
            if (counter == arraySize)           //If the counter is equal to the size of the array
            {                                   //the array must be resized
                arraySize +=2;
                int *temp = new int[arraySize];
                for (counter = 0; counter < arraySize; counter++)
                {
                    temp[counter] = arrayPtr[counter];
                }
                delete [] arrayPtr;
                arrayPtr = temp;
                counter ++;                     //the counter has to be reset to it's original position
            }                                   //which should be +1 of the end of the old array
            cin >> arrayPtr[counter];
            if (arrayPtr[counter] == sentinel)
            {
                cout << "Sentinel Value given, data entry ending.\n";
                break;
            }
            counter ++;
        }
    

    这会产生一个意外的操作,它不等待哨兵值,而是开始列出内存中超过该点的整数(因为没有边界检查)。

    下一个问题是我的排序函数拒绝运行。我试着在5个值上进行测试,程序在到达代码的特定部分时崩溃。

    sorting (arrayPtr);
    

    但函数本身看起来是这样的:

    void sorting (int *arr)
    {
        int count = 0, countTwo = 0, tempVal;
    
        for (count = 0; arr[count] != 999999; count++)          //I figured arr[count] != 999999 is easier and looks better
        {                                                       //A bunch of if statements
            for (countTwo = 0; arr[countTwo] != 99999; countTwo++)
            {
                if (arr[countTwo] > arr[countTwo+1])
                {
                    tempVal = arr[countTwo];
                    arr[countTwo] = arr[countTwo+1];
                    arr[countTwo+1] = tempVal;
                }
            }
        }   
    }
    

    在此问题上的任何帮助都将不胜感激。

    链接到我的源代码:

    http://www.mediafire.com/file/w08su2hap57fkwo/Lab1_2336.cpp

    由于社区反馈,此链接将保持活动状态

    下面的链接是我更正的源代码。对其进行注释是为了更好地突出我所犯的错误以及修复这些错误的答案。

    http://www.mediafire.com/file/1z7hd4w8smnwn29/Lab1_2336_corrected.cpp

    1 回复  |  直到 7 年前
        1
  •  0
  •   GiantSpaceFlyingElvis    7 年前

    我在代码中发现的第一个问题是for循环,其中计数器从0到arraySize-1,循环的最后两次迭代将访问arrayptr越界。

    接下来,在 if (counter == arraySize) 有一个 counter++; counter 正在索引超出界限的数组。

    最后,在排序函数中,内部循环查找错误的值(99999而不是999999),因此它从不停止并超出界限。为了防止这种错误,您应该定义 sentinel 作为未命名命名空间中的常量,并通过代码使用它,而不是键入999999(这很容易出错…)。