1596 - Bug Hunt

用map<char, map<int, string> > Mem 类型模拟内存,数组名对应的索引的值

用map<char, int> Size 来存放数组对应的大小

假设只有未初始化和越界的错误。

即对每个表达式进行扫描,从里到外依次检验每个数组是否越界,是否未初始化。如果只有数组,则最外面的数组是声明,如果是赋值表达式,那么就不是声明。每次到声明就把数组名和对应的大小记下来。

</pre><pre name="code" class="cpp">#include <iostream>
#include <vector>
#include <sstream>
#include <map>
#include <cstdlib>
using namespace std;
typedef map<char, map<int, string> > Mem;
typedef map<char, int> Size;
Mem mem;
Size siz;
bool bug(const string &s, bool declare, string &val, string assignment = "-") {
	int pos = s.find_last_of('['), idx;
	if (pos == string::npos)val = s;
	else idx = atoi(s.substr(pos + 1, s.find_first_of('[') - pos - 1).c_str());
	for (int i = pos; i >= 0; i--) {
		if (s[i] != '[') {
			if (i == 0 && declare == true) {							//如果是声明
				siz[s[i]] = idx;
			}else {
				if (idx >= siz[s[i]] || idx < 0)return true;			//越界
				if (i == 0 && declare == false && assignment != "-")mem[s[i]][idx] = assignment;		//如果不是声明且是赋值
				if (mem[s[i]].count(idx) == 0)return true;				//未初始化
				val = mem[s[i]][idx];									//模拟访存
				idx = strtol(mem[s[i]][idx].c_str(), NULL, 10);			
			}
		}
	}
	return false;
}
bool debug(string & s) {
	string val; int e = s.find('=');
	string rval; string c;
	if (e == string::npos) {			//声明语句
		return bug(s, true, rval);
	}
	else {			//赋值语句
		string lhs = s.substr(0, e), rhs = s.substr(e + 1);
		if (bug(rhs, false, rval)) return true;		//未初始化或越界
		if (bug(lhs, false, c, rval))return true;		//未初始化或越界
		return false;
	}
}
int main() {
	string s;
	while (cin >> s && s != ".") {
		mem.clear();
		siz.clear();
		int cnt = 1;
		bool dbug = false;
		if (debug(s)) { cout << cnt << endl; dbug = true; while (cin >> s && s != "."); continue; }
		else cnt++;
		while (cin >> s && s != ".") {
			if (debug(s)) { cout << cnt << endl; dbug = true; while (cin >> s && s != "."); break; }
			else cnt++;
		}
		if (dbug == false)cout << 0 << endl;
	}
	system("pause");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值