Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stl

I am getting a bad_alloc exception in my program.

These are the constraints:

  • 1 <= T <= 10
  • The length of each string is at most 100000 and contains only lower case characters.

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;
}
like image 360
Avinash Avatar asked Dec 30 '11 07:12

Avinash


1 Answers

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?

like image 88
ChrisWue Avatar answered Sep 26 '22 17:09

ChrisWue