在抛出 'std::bad_alloc' 的实例后调用终止 what(): std::bad_alloc 中止

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

本文关键字:std bad alloc what 终止 中止 调用 实例      更新时间:2023-10-16

我的程序中出现了bad_alloc异常。

约束条件如下:

  • 1 <= T <= 10
  • 每个字符串的长度不超过100000,且只包含小写字符。

有了这些限制,我无法弄清楚为什么我的程序得到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;
}

因为你在这里所做的:

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

是:创建长度为0,1,2,…的N子字符串。N这些将要消耗的内存总量是:1 + 2 + 3 + ... + N字节。有了老高斯,你会发现前N个数的和是:N * (N + 1) / 2

现在,如果您设置N = 100,000,这将导致大约5GB的内存消耗-这比最大值要大。你的程序通常有2GB的地址空间,除非你在64位系统上运行它。

编辑:我不知道你想解决什么问题,但你的实现似乎很奇怪:

你从来没有使用过计算的后缀:你使用的SuffixArray的唯一函数是lcp,它没有引用存储的suffixes向量。那么你首先需要它们做什么呢?