当我尝试运行它时出现段错误:
#define FILE_NAME "test.html"
#define STRING_ARRAY_SIZE 1000000
int main() {
fstream file;
string line = "";
string string_array [STRING_ARRAY_SIZE];
int i = 0;
file.open(FILE_NAME);
while(getline(file, line)) {
string_array[i] = line;
i++;
cout << line << endl;
}
file.close();
}
相反,当我尝试编译它时,它起作用了:
#define FILE_NAME "test.html"
#define STRING_ARRAY_SIZE 100000
int main() {
fstream file;
string line = "";
string string_array [STRING_ARRAY_SIZE];
int i = 0;
file.open(FILE_NAME);
while(getline(file, line)) {
string_array[i] = line;
i++;
cout << line << endl;
}
file.close();
}
事实证明,唯一的区别是数组的大小。为什么到100000就可以,到1000000就不行?最大尺寸是多少?谢谢。
最佳答案
该限制是特定于系统(不仅是硬件,还包括软件,尤其是操作系统和运行时)的。另见 this question与你的非常相似。
尽量避免太大call stack frames .如今,在台式机或服务器机器上,我建议最大的调用堆栈帧最多使用几十 KB(而且通常更少,即数百字节)——特别是对于中间 - 非叶 - 或递归函数。一个典型的系统有一个可以增长到几兆字节的机器堆栈(但在嵌入式微 Controller 上,或者在 Linux 内核内部,它可能是几千字节!)。对于多线程应用程序,它应该少一些(因为每个线程都有自己的堆栈)。
在 Linux 和 Posix 系统上,您可以使用 setrlimit(2)使用 RLIMIT_STACK
进行系统调用以降低(有时可能会略微增加)堆栈限制。在带有 bash
shell 的终端中,使用内置的 ulimit -s
。
以下GCC您可能感兴趣的选项:-fstack-usage
、-Wframe-larger-than=
、-fstack-split
在你的代码中,考虑替换
string string_array [STRING_ARRAY_SIZE];
与
vector<string> string_vector;
和替换
string_array[i] = line;
i++;
与
string_vector.push_back(line);
关于c++ - 局部数组变量的最大大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24904047/