int arr2[5]={5,4,3,2,1};
sortArray(arr2, 5);
void sortArray(int data[], int size)
{
int i, j;
int element;
for (i = 1; i < size; i++)
{
element = data[i];
j = i-1;
while (j >= 0 && element < data[j])
{
data[j+1] = data[j];
j--;
}
data[j] = element;
}
}
My function gets this error and my array look like this {5,5,5,5,5} when the function ends, why so?
As stated above: during the first iteration of your for loop, after the while loop has executed, j is decremented to -1 and then used in as the index in your data array; this is the cause of your stack corruption.
Some more info about stack corruption: when you reference a certain index of your array (IE data[j]), you’re basically saying ‘start at the location in memory pointed to by the pointer named data, add j * sizeof(int) bytes, and grab that value’.
In code,
data[j]is equivalent to*(data + (j * sizeof(int))). When you give a negative value, you reference memory not allocated to the data array; in this case the memory happens to be part of the stack. Because you’re modifying it, you get the stack corruption error.