Avinash
Avinash

Reputation: 13257

terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Aborted

I am getting a bad_alloc exception in my program.

These are the constraints:

With those constraints, I am unable to figure out why my program is getting bad_alloc.

#include <string>
#include <algorithm>
#include <iostream>
#include <vector>

class SuffixArray {
    std::vector<std::string> suffixes;
    size_t N;
public:
    SuffixArray(std::string& s) {
        N = s.length();
        suffixes.resize(N);
        for (size_t i = 0; i < N; i++)
            suffixes[i] = s.substr(i);
        std::sort(suffixes.begin() , suffixes.end());
    }
    ~SuffixArray() {
    }
    size_t lcp(std::string& s, std::string& t) {
        size_t N = std::min(s.length(), t.length());
        for (size_t i = 0; i < N; i++)
            if (s[i] != t[i]) 
                return i;
        return N;
    }    
};

int main ( int argc, char **argv) {
    int T;
    std::cin >> T;
    std::vector<size_t> results;

    for ( int i = 0; i < T; i++) { 
        std::string str;
        std::cin >> str;
        SuffixArray sa(str);
        size_t sol = 0;

        for ( std::string::iterator it = str.begin(); it != str.end(); ++it) {
            std::string target = std::string(it, str.end());
            sol += sa.lcp(str, target);            
        }
        results.push_back(sol);
    }
    for ( std::vector<size_t>::iterator it = results.begin(); it != results.end(); ++it) 
        std::cout << *it << std::endl;
    results.clear();

    return 0;
}

Upvotes: 5

Views: 32507

Answers (1)

ChrisWue
ChrisWue

Reputation: 19020

Because what you do here:

  for (size_t i = 0; i < N; i++)
        suffixes[i] = s.substr(i);

is: Create N sub strings of lengths 0, 1, 2, ..., N The total amount of memory these are going to consume is: 1 + 2 + 3 + ... + N bytes. Having good old Gauss at your hand you will find that the sum of the first N numbers is: N * (N + 1) / 2

Now if you set N = 100,000 this results in about 5GB of memory consumption - which is larger than the max. 2GB address space your program usually has unless you run it on a 64bit system.

Edit: I don't know what the problem is you are trying to solve however your implementation seems strange:

You never ever use the computed suffixes: The only function of SuffixArray you are using is lcp which makes no reference to the stored suffixes vector. So what you need them for in the first place?

Upvotes: 15

Related Questions