2

Visual Studio Debug is showing the exception "Vector subscript out of range" (only debug mode) but I can't detect it. There's nothing wrong, it's selection sort algorithm.

Source code:

#include <iostream>
#include <vector>

using namespace std;

template<typename T>
void ascending_sort(vector<T> & list) {
    size_t i, j, index;

    for (i = 0; i < list.size() - 1; i++) {
        index = i;

        for (j = i + 1; j < list.size(); j++) {
            if (list[j] < list[index]) {
                index = j;
            }
        }

        if (index != i) {
            T item = list[i];

            list[i] = list[j];
            list[j] = item;
        }
    }
}

int main(int argc, char * argv[]) {
    vector<int> list = { 5, 1, -14, 8 };

    ascending_sort(list);

    for (size_t i = 0; i < list.size(); i++) {
        cout << list[i] << endl;
    }

    return 0;
}

Output:

0
5
-14
8
Danilo
  • 175
  • 1
  • 11

1 Answers1

5

In ascending_sort(),

if (index != i) {
    T item = list[i];

    list[i] = list[j];
    list[j] = item;
}

You should use index instead of j, which might be list.size() after the for loop, then list[j] will cause out of range issue. Change it to

if (index != i) {
    T item = list[i];

    list[i] = list[index];
    list[index] = item;
}

std::vector::operator[] doesn't perform bounds checking, it leads to undefined behaviour when subscript is out of range. It seems VS will throw exception in DEBUG mode, but this is not guaranteed by the standard. You could use std::vector::at instead, which will throw std::out_of_range when subscript is out of range.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405