0

when I run the following code written to implement the suffix array algorithm, I get a segmentation fault. Can anyone please help me in solving it? I think the issue is with the while since cout in all other places work properly

Following is the code is used

vector<int> suffixArray(string s, int n)
{
    vector<int> p(n); // Indexes 
    vector<int> c(n); // Classes

    {
        vector<pair<char, int>> a(n);

        for (int i = 0; i < n; i++)
        {
            a[i] = {s[i], i};
        }

        sort(a.begin(), a.end());

        for (int i = 0; i < n; i++)
            p[i] = a[i].second;
        c[p[0]] = 0;

        for (int i = 1; i < n; i++)
        {
            if (a[i].first == a[i - 1].first)
            {
                c[p[i]] = c[p[i - 1]];
            }
            else
            {
                c[p[i]] = c[p[i - 1]] + 1;
            }
        }
    }
    int k = 0;

    while (pow(2, k) < n)
    {
        vector<pair<pair<int, int>, int>> a;

        for (int i = 0; i < n; i++)
        {
            a[i] = {{c[i], c[(int)(i + pow(2, k)) % n]}, i};
        }

        sort(a.begin(), a.end());
        for (int i = 0; i < n; i++)
            p[i] = a[i].second;
        c[p[0]] = 0;

        for (int i = 1; i < n; i++)
        {
            if (a[i].first == a[i - 1].first)
            {
                c[p[i]] = c[p[i - 1]];
            }
            else
            {
                c[p[i]] = c[p[i - 1]] + 1;
            }
        }
        k++;
    }
    return p;
}

enter image description here Thank You

Shakya Peiris
  • 504
  • 5
  • 11
  • Please learn how to use a debugger to step through your code to figure out where your logic is wrong. Most likely you are indexing one of the vectors out-of-bounds somewhere. In any case, please always provide a complete [mre] here, including the input used which causes the problem. See [ask]. – user17732522 May 25 '22 at 04:14
  • If `pow` is `std::pow`, then `pow(2, k)` is almost surely wrong. `pow` acts on floating point numbers. It is not guaranteed to generate the correct result expected for integer arithmetic. – user17732522 May 25 '22 at 04:18
  • In the land of binary, 2 to the xth power is the same as `1 << x`, up until you run out of bits. – user4581301 May 25 '22 at 04:58
  • The segmentation fault occurs when you set `a[i]`, because `a` is empty. If you initialize `a` with default pairs, the assignment works: `vector<...> a(n)`. – M Oehm May 25 '22 at 05:20

0 Answers0