c++ - Getting segmentation fault *sometimes* from an attempt at a selection sort implementation -
i've attempted debug on own, can't figure out! i'm getting segmentation faults when running code, when there's not seg fault runs fine , works. guidance appreciated, thanks! also, please keep in mind i'm new c++.
here's have far:
#include <iostream> #include <vector> using namespace std; vector<int> selection_sort(vector<int> numbers) { int lowest_number_index; int lowest_number; int starting_size = numbers.size(); vector<int> sorted_numbers; (int = 0; < numbers.size(); ++i) { // find lowest number if (numbers[i] <= lowest_number) { lowest_number_index = i; lowest_number = numbers[lowest_number_index]; } // found it! let's add other array // , remove one. if (i == numbers.size() - 1 && numbers.size() != 1) { sorted_numbers.push_back(lowest_number); numbers.erase(numbers.begin() + lowest_number_index); // if we're not done sorting if (sorted_numbers.size() != starting_size) { lowest_number_index = 0; lowest_number = numbers[lowest_number_index]; // continue sorting = -1; continue; } } else if (numbers.size() == 1) { sorted_numbers.push_back(numbers[i]); } } return sorted_numbers; } int main() { vector<int> to_sort { 15, 2, 41, 5, 4, 5, 4, 6 }; to_sort = selection_sort(to_sort); cout << "sorted: "; (auto = to_sort.begin(); != to_sort.end(); ++it) { cout << *it << " "; } cout << endl; }
the function has undefined behaviour because there used uninitialized variable lowest_number
int lowest_number; ^^^^^^^^^^^^^ //... (int = 0; < numbers.size(); ++i) { // find lowest number if (numbers[i] <= lowest_number) { ^^^^^^^^^^^^^^^^^^^^^^^^^^^
take account variable lowest_number_index
uninitialized.
int lowest_number_index;
Comments
Post a Comment