Reputation:
I know question sounds dumb, I can't really figure out what is wrong in this code?
void sort(int *arr, int size)
{
int min = 0;
for (int i = 0; i < size - 1; i++)
{
for (int j = i; i < size; j++)
{
if (arr[min] > arr[j])
{
min = j;
}
}
if (min != i)
{
Swap(&arr[i], &arr[min]);
}
}
}
The following code should sort the arr
but it is giving segmentation fault.
I ran this code via debugger and it says the value of j
at line
for (int j = i; i < size; j++)
something like 3234
(not initialized) and program ends. But j
should be 0
.
Upvotes: 2
Views: 62
Reputation: 144695
There are 3 problems in your sort
function:
for
loop uses i
instead of j
. j
is initialized but the test always succeeds and the loop goes on, letting the code access arr
beyond its boundaries, causing undefined behavior.min
should initialized to i
inside the outer loop,j
should be initialized to i + 1
is the inner loop (minor).Here is a corrected version:
void sort(int *arr, int size) {
for (int i = 0; i < size - 1; i++) {
int min = i;
for (int j = i + 1; j < size; j++) {
if (arr[min] > arr[j]) {
min = j;
}
}
if (min != i) {
Swap(&arr[i], &arr[min]);
}
}
}
Upvotes: 1