-1

I am trying to sort a list of indexes based on a list of string, and I receive bellow error - Segmentation fault. I cannot understand why I receive this error and how to solve it?

#include <iostream>
#include <string.h>
using namespace std;

int main() {
    int size = 5;
    char* mass[size];
    int num[size];

    for(int i = 0; i < size; i++) {
        mass[i] = new char[20];
        num[i] = i;
        cin >> mass[i];
    }
    
    for(int i = 0; i < size; i++){
        for(int j = size; j > i; j--)
            if(strcmp(mass[num[j-1]], mass[num[j]]) > 0){
                int tmp = num[j-1];
                num[j-1] = num[j];
                num[j] = tmp;
            }
    }
    
    for(int i = 0; i < size; i++){
        cout << mass[num[i]] << ", ";
    }

    return 0;
}
mrRaduga
  • 11
  • 3
  • 1
    mixing variable length array and proper dynamic arrays for fixed size arrays is kinda confusing. Why not `char mass[size][20];` (and `const int size = 5;`) ? I suppose you used flawed learning material. Read [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) and about `std::array`, `std::string` and `std::vector` – 463035818_is_not_an_ai May 10 '22 at 12:02
  • Is this C++ or C wrapped in a C++ layer? Why not use `std::vector` or any of the ``s? `#include ` is already a big smell – JHBonarius May 10 '22 at 12:03
  • 3
    At `mass[num[j]]` and `num[j] = tmp` you are accessing past the end of the array when `j == size`. – 001 May 10 '22 at 12:07

1 Answers1

0

In the inner loop you start with j = size and then num[j] is an out-of-bounds array access.

In modern C++ you would solve this like this:

#include <iostream>
#include <array>
#include <algorithm>

int main() {
    const int size = 5;
    std::array<std::string, size> mass;
    std::array<int, size> num;

    for (int i = 0; i < size; i++) {
        std::cin >> mass[i];
        num[i] = i;
    }

    std::ranges::sort(num, [mass](int a, int b) { return mass[a] <= mass[b];});

    for(int i = 0; i < size; i++){
        std::cout << mass[num[i]] << ", ";
    }
    std::cout << std::endl;

    return 0;
}
Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42