首页 > 解决方案 > -1073741571 (0xC00000FD) 代码块 C++ 中的错误

问题描述

我需要生成大量的随机字母数字字符串,大小小于 10000 是可以的,但是当我尝试创建大小为 100,000 时,它返回错误 -1073741571 (0xC00000FD) 并且我的代码不会运行。请告诉我错误是什么以及如何解决。

以下是我的代码:

#include <iostream>
#include <ctime>
#include <unistd.h>

using namespace std;

string gen_random(const int len) {

    string tmp_s;
    static const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";

    srand(rand() ^ (unsigned) time(NULL) * getpid());

    tmp_s.reserve(len);

    for (int i = 0; i < len; ++i)
        tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];

    return tmp_s;

}

bool repeat(string target, string arr[],int arr_size)
{
    for (int i=0; i<arr_size; i++)
    {
        if (arr[i].compare(target) == 0)
            return true;
    }
    return false;
}

int main(int argc, char *argv[])
{

    const int n = 100000;
    string data_set[n];

    for (int i=0; i<n; i++)
    {
        string s = gen_random(4) + "." + gen_random(5) + "@" + gen_random(5);

        if (!repeat(s,data_set,n))
          data_set[i] = s;
        else
            i--;
    }

    for (int i=0; i<n; i++)
        cout << data_set[i] << endl;

    return 0;
}

标签: c++

解决方案


错误是由于以下几行:

    const int n = 100000;
    string data_set[n];

因为您将它存储在函数堆栈上,所以程序的堆栈不够大,无法容纳导致错误的它。如果你减小它的大小,n它编译并运行良好。

为了避免这种情况,更好地使用堆分配new

最好的方法是使用 std::vector<std::string> Here is the modify of the code here:

#include <iostream>
#include <ctime>
#include <unistd.h>
#include <iostream>
#include <vector>
#include <string>

using namespace std;

string gen_random(const int len) {

    string tmp_s;
    static const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";

    srand(rand() ^ (unsigned) time(NULL) * getpid());

    tmp_s.reserve(len);

    for (int i = 0; i < len; ++i)
        tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];

    return tmp_s;

}

bool repeat(string target, std::vector<std::string> arr)
{
    for (int i=0; i<arr.size(); i++)
    {
        if (arr[i].compare(target) == 0)
            return true;
    }
    return false;
}

int main(int argc, char *argv[])
{

    const int n = 100000;
    vector<string> data_set(n);

    for (int i=0; i<n; i++)
    {
        string s = gen_random(4) + "." + gen_random(5) + "@" + gen_random(5);

        if (!repeat(s,data_set))
          data_set[i] = s;
        else
            i--;
    }

    for (int i=0; i<n; i++)
        cout << data_set[i] << endl;

    return 0;
}


推荐阅读