user7854936
user7854936

Reputation:

nested for loop value of not initialized

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.

debuger screenshort

Upvotes: 2

Views: 62

Answers (2)

chqrlie
chqrlie

Reputation: 144695

There are 3 problems in your sort function:

  • The test in the inner 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

Mankalas
Mankalas

Reputation: 410

In your second for loop, it should be j < size, not i < size.

Upvotes: 2

Related Questions