c++ - -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;
}
解决方案
错误是由于以下几行:
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;
}
推荐阅读
- binary - 展平二叉树以列出(有序)
- node.js - 如何从使用 axios 的 API 调用中获取的值设置 FulsionText?
- java - 如何改进我的 java 代码以减少 android studio 上的内存垃圾?
- python - 如何使用我的二次方程程序绘制抛物线?
- tree - 使用 7-2+3 后缀表示法的翻译方案的可能树
- python - PySpark join 返回一个空字典而不是 None
- javascript - 在嵌套数组中查找值
- ios - 在另一个 tableViewController 的子视图中添加一个新的 TableView
- java - 如何修复 Gradle Build 中的“无法处理 kafka-clients-1.1.1.jar”错误
- assembly - 如何在此汇编代码中找到错误?