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.
Usually when doing a nested loop of this kind, the inner loop is set to start at outer loop + 1. So that you don't end up with values like this Array1[counter2 + 1]
which leads to an illegal memory access outside the bounds of the array on the final iteration of the loop.
Even with that fixed, the sorting logic is incorrect. What you are trying to do is known as a selection sort where you compare each element of the array to the rest of elements in n^2 time complexity. You have to obtain the lowestNum_index
for each iteration of the outer loop, not the entire array. Here's how I would do a selection sort.
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
}
}
Since your swap function accepts two pointers, using Array[i]
will lead to illegal memory access as the []
operator dereferences the array to the value at i
, you have to use the &
operator to get the address for that location. i.e.
Array[i] = *(Array + i)
&Array[i] = Array + i // <--- essentially cancels the dereference operator
Edit: Intialize lowestIdx = i
on each outer loop