函数超过堆栈大小,请考虑将一些数据移动到堆 (C6262)

Function exceeds stack size, consider moving some data to heap (C6262)

本文关键字:移动 数据 C6262 堆栈 函数      更新时间:2023-10-16

我正在尝试通过制作密码生成器来学习C++,当我快完成时,我收到了一个警告(警告 C6262 函数使用堆栈的"20044"字节:超过/analyze:堆栈大小"16384"。 考虑将一些数据移动到堆中。 而且由于我是C++的初学者,现在才掌握基础知识,我不知道该怎么办。

由于我在函数中有 2 个数组,我试图将它们移出主函数,它确实降低了它使用的字节数 (20100(,它仍然太高了。我试图阅读Microsoft的错误指南,但我不知道堆或将所述数据移动到

堆中C++代码如下:

#include <iostream>
#include <random>
using namespace std;
class Randomer {
// random seed by default
std::mt19937 gen_;
std::uniform_int_distribution<size_t> dist_;
public:
/*  ... some convenient ctors ... */
Randomer(size_t min, size_t max, unsigned int seed = std::random_device{}())
: gen_{ seed }, dist_{ min, max } {
}
// if you want predictable numbers
void SetSeed(unsigned int seed) {
gen_.seed(seed);
}
size_t operator()() {
return dist_(gen_);
}
};
string alphabet{ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n','o','p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z' };
string specialchars{ ' ','!','#','$', '%', '&','(',')','*','+','-','.','/',':',';','<','=','>','?','@' };
Randomer rand1{ 0,2 };
Randomer randint{ 0,9 };
Randomer randalpha{ 0,26 };
Randomer randspecial{ 0,20 };
int main()
{
while (true) { //This loop is to restart the program if an invaild response is detected.
int i;
int lengthofpassword = 8;
cout << "Do you want to generate a password or to type in a existing password to make it stronger?nn(1 for generation, 2 for existing password)n";
cin >> i;
int g = 0;
if (i == 1) {
cout << "nWhat is the length of the password?n";
cin >> lengthofpassword;
while (g <= lengthofpassword -1) {
//if (rand() == 0) {//numb
//  cout << randint();
//}
//else if (rand() == 1) {//letter
//  cout << alphabet[randalpha()];
//}
switch (rand1())
{
case 0:
cout << alphabet[randalpha()];
break;
case 1:
cout << randint();
break;
case 2:
cout << specialchars[randspecial()];
break;
default:
break;
}
g = g + 1;
//cout << "nn" << g << "nn";
}
cout << "n";
system("pause");
return 0;
}
else if (i == 2) {
cout << "n";
system("pause");
return 0;
}
else {
cout << "n";
cout << "Invaild Response!n";
}
}
//  system("pause");
return 0;
}

尝试将其压缩以进行堆栈溢出不起作用。 虽然它还没有坏并且按预期工作,但我觉得我现在应该学习这类东西,而不是以后。

将某些内容从堆栈移动到堆基本上是使用new显式分配新对象,而不是声明变量。

在您的情况下,您可以将四个Randomer xxx变量替换为Randomer* xxx = new Randomer{...},并在循环结束时将其删除。尽管在循环中重新创建 PRNG 没有多大意义,也许您应该将Randomer对象移动到main()之外。

std::mt19937伪随机数生成器实际上是一个巨大的对象,你在循环中创建了很多伪随机数生成器。你应该做的是在开始时创建一个,并在你Randomer对象之间共享它,例如,通过在构造函数中向它们传递一个指针。(您可以将它们或Randomer对象移动到堆中,但创建大量对象只是浪费性能,并且没有充分的理由拥有多个对象。