c++ - 没有递归的堆栈溢出?
问题描述
据我所知,我的代码没有递归,但我得到了异常 0xC00000FD。根据 Rider For Unreal Engine 的说法,它发生在 main 函数中。在反编译的代码中遇到它
mov byte ptr [r11], 0x0
它工作正常,然后当我第二次运行它时,为了确保它正常工作,它突然坏了。现在它每次都会给出这个例外。这是我的代码:
// Language.cpp
#include <fstream>
#include <iostream>
#include <regex>
#include <stdexcept>
#include <string>
#include "Lexer/Lexer.h"
#include "Util/StrUtil.h"
int main(int argc, char* argv[])
{
std::string line, fileString;
std::ifstream file;
file.open(argv[1]);
if(file.is_open())
{
int lines = 0;
while(file.good())
{
if (lines > 10000)
{
std::cerr << "Whoa there, that file's a little long! Try compiling something less than 10,000 lines." << '\n';
return -1;
}
getline(file, line);
fileString += line + (char)10;
lines++;
}
}
fileString += (char)0x00;
std::string arr[10000];
int arrLength = StrUtil::split(fileString, "\n", arr);
Line lines[10000];
Lexer::lex(arr, arrLength, lines);
return 0;
}
// Lexer.cpp
#include "Lexer.h"
void Lexer::lex(std::string (&str)[10000], int length, Line (&lines)[10000])
{
for (int i = 0; i < length; i++)
{
}
}
// StrUtil.cpp
#include "StrUtil.h"
#include <stdexcept>
#include <string>
int StrUtil::split(std::string str, std::string delimiter, std::string (&out)[10000])
{
int pos = 0;
out[0] = str;
while (out[pos].find(delimiter) != std::string::npos)
{
const size_t found = out[pos].find(delimiter);
out[pos + 1] = out[pos].substr(found + delimiter.length());
out[pos] = out[pos].substr(0, found);
pos++;
}
return pos + 2;
}
对于自定义类型,Line
是一个Token
s 数组,它们只是 < TokenType
, std::string
> 对。
解决方案
据我所知,我的代码没有递归
实际上,显示的代码中没有递归。缺乏递归并不意味着你不会溢出堆栈。
没有递归的堆栈溢出?
是的,这个程序可能会在某些系统上溢出堆栈。
std::string arr[10000];
的典型大小std::string
为 32 字节(在不同的语言实现之间可能会有很大差异)。10000 个字符串是 312 kiB。大多数桌面系统上的执行堆栈是一到几 MiB。该数组大约是程序最深堆栈帧中必须容纳所有自动变量的内存的三分之一。剩余的堆栈内存不足以满足程序的其余部分是非常可行的,尤其是考虑到您还有另一个庞大的Line
对象数组。
要修复程序,请不要在自动存储中分配诸如此类的大量变量。
推荐阅读
- chef-infra - Chef:是否可以定义一个使用模板的 Chef 资源,并从另一个食谱中调用它?
- ios - 摆脱 Bolts 框架中的 UIWebView(解析框架依赖)
- laravel - 按钮打开新窗口
- ios - 拦截 iOS 深层链接
- esp32 - ESP32 的有限闪存低于声明为 SPIFFS 的 4mb
- c - 获得段错误
- c# - 验证 Zip 文件夹中的内容是否存在于 XML 元数据中且没有差异
- excel - Excel - VBA 宏 - 在特定工作表处停止代码
- javascript - “剪切”元素的一部分(作为滚动的行为)
- visual-studio-code - VS Code:有没有办法将我的调试会话关联到特定终端?