我正在编写自己的编程语言(用于学习)而且我有错误。
Debug Assertion Failed!
Program: C:/Path/MSVCP140D.dll
Line: 1232
Expression vector subscript out of range
For information how your progr... (Not important)
产生错误的函数:
Parser::Parser(std::vector<std::string> toks) {
for (unsigned i = 0; i < toks.size(); i++) {
if (toks[i++] + " " + toks[i] == "PRINT STRING:") {
std::cout << toks[i += 1] << std::endl;
}
if (toks[i++] + " " + toks[i] == "ASM STRING:") {
std::cout << "FOUND ASM" << std::endl;
}
}
}
生成分支的功能:
Lexer::Lexer(std::string source){
std::string tok = "";
std::string string = "";
int state = 0;
for (int i = 0; i <= source.length(); i++) {
tok += source[i];
if (tok == " ") {
if (state == 1) {
string += tok;
} else tok = "";
} else if (tok == "\n") {
tok = "";
} else if (tok == "print") {
tokens.push_back("PRINT");
tok = "";
} else if (tok == "asm") {
tokens.push_back("ASM");
tok = "";
} else if (tok == "\"") {
if (state == 0) {
state = 1;
} else if (state == 1) {
tokens.push_back("STRING:");
tokens.push_back(string);
string = "";
state = 0;
tok = "";
}
} else if (state == 1) {
string += source[i];
tok = "";
}
}
}
输出:
toks that are generated: PRINTSTRING:print expASMSTRING:ams exp
toks one by one:
PRINT
STRING:
print exp
ASM
STRING:
ams exp
答案 0 :(得分:2)
我相信你想要增加i
的唯一时间就在这里:
for (unsigned i = 0; i < toks.size(); i++)
// ^^^
在没有检查的循环中, toks[i++]
然后toks[i]
将变得非常糟糕。如果是toks[i + 1]
,请记住i + 1
无法到达toks.size()
吗?同样如下:toks[i += 1]
。
也许你应该在循环体中添加toks[i]
,toks[i + 1]
,toks[i + 2]
这样的内容:
for (unsigned i = 0; i + 2 < toks.size(); i += 3)
另一个问题是:
for (int i = 0; i <= source.length(); i++)
// ^^
// should be <
我不知道是不是全部。