Dynamically allocated arrays and HEAP corrupted

时间:2019-05-31 11:52:44

标签: c++ dynamic-arrays heap-corruption

I am trying to write a program that takes inputs as a dynamic array and sorts them from lowest to highest and then displays from highest to lowest. However, I get a debugging error that states "HEAP CORRUPTION DETECTED: after Normal block (#182) at 0x010CE3E8. CRT detected that the application wrote to memory after end of heap buffer."

Well, the program builds and runs successfully. However, when I try to exit the program it takes a really long time and I receive the error.

void insert_Array(int Array1[], int array_size)
{
    for (int counter = 0; counter < array_size; ++counter)
    {
         cout << " Please enter the " << counter << " number : ";
         cin >> Array1[counter];
    }
    return;
}

void swap(int* a, int* b)
{
    int holder = *a;
    *a = *b;
    *b = holder;
}

void sort_Array(int Array1[], int array_size)
{
    int lowestNum_index;
    for (int counter1 = 0; counter1 < array_size; ++counter1)
    {
        for (int counter2 = counter1; counter2 < array_size; ++counter2)
        {
            if (Array1[counter2] < Array1[counter2 + 1])
                lowestNum_index = counter2;
            else
                lowestNum_index = counter2 + 1;
        }
        swap(Array1[counter1], Array1[lowestNum_index]);
    }
    return;
}

Main function

int* npointer = new int[nNumbers];
insert_Array(npointer, nNumbers);
sort_Array(npointer, nNumbers);
cout << " The number you desired is " << nNumbers << endl;

cout << " The numbers in the array from  high to low are ";
for (int i = 0; i < nNumbers; ++i)
{
    cout << *(npointer + nNumbers - i) << " ";
}

cout << endl;
delete [] npointer;

When I run the program successfully sorts the numbers that I give from highest to lowest.

HEAP CORRUPTION DETECTED: after Normal block (#182) at 0x010CE3E8. CRT detected that the application wrote to memory after end of heap buffer.

1 个答案:

答案 0 :(得分:0)

通常,当执行此类嵌套循环时,将内部循环设置为从外部循环+ 1开始。这样一来,您就不会得到诸如Array1[counter2 + 1]这样的值,而这会导致非法的内存访问在循环的最终迭代中超出数组范围。

即使已修复,排序逻辑也不正确。您尝试做的事情称为选择排序,您可以在数组中将每个元素与其余元素以n ^ 2的时间复杂度进行比较。您必须为外循环的每个迭代而不是整个数组获取lowestNum_index。这就是我进行选择排序的方式。

void sort_Array(int Array[], int array_size)
{
  for (int i = 0; i < array_size; ++i)
  {
    int lowestIdx = i; // <-- always starts at i
    for (int j = i + 1; j < array_size; ++j)
      if (Array[j] < Array[i])
        lowestIdx = j;

    swap(&Array[lowestIdx], &Array[i]); // <--- note the & symbol to pass by reference
  }
}

由于交换函数接受两个指针,使用Array[i]会导致非法的内存访问,因为[]运算符将数组取消引用为i的值,因此您必须使用{ {1}}运算符以获取该位置的地址。即

&

编辑:在每个外部循环上初始化Array[i] = *(Array + i) &Array[i] = Array + i // <--- essentially cancels the dereference operator