【问题标题】:Why am I hitting string subscript out of range?为什么我的字符串下标超出范围?
【发布时间】:2014-12-03 22:14:02
【问题描述】:

我正在尝试使用这个函数,我能够调试并将其缩小到这个名为 addrstore 的变量。我不知道为什么它给了我这个错误。我已经尝试过变量、设置数字等,但我似乎无法让它在没有它出错的情况下工作。我可以忽略该错误,并且该程序似乎工作得很好,但每次我运行它时,它都会给我一个错误,“字符串下标超出范围”。

这里是代码

void loading(string file){
ifstream object;
BYTE var;
ADDRESS addr;
string input;

object.open(file);
if (!object){
    cout << "ERROR: Could not load " << file << endl;
}
else{
    string line;
    string addrstore;
    cout << "loaded the file " << file << endl;
    while (!object.eof()){
        getline(object, line);
        addr = 0;
        if (line[0] == 'T'){
            for (int x = 1; x < 7; x++){
                addrstore[x - 1] = 0;
                //addrstore[x - 1] = line[x];
            }
            addr = numconvert(addrstore);
        }
        int i = 7;
        while (line.size() != 0 && line[0] == 'T' && i < line.size()){
            input = line[i] + line[i + 1];
            var = numconvert(input);
            PutMem(addr, &var, 0);
            i += 2;
            addr++;
        }
    }
    object.close();
}
}

【问题讨论】:

  • 这是 C++,不是 C。请更新标签。 :)
  • ...但我怀疑问题在于您指的是 line[i+1],而 line 实际上只有 line[0] 到 line[i-1] 的元素。
  • 您在使用line[0] 时未检查您的line 是否为非空。另请参阅stackoverflow.com/questions/5431941/…
  • 问题的原因是行addrstore[x - 1] = 0; 因为addrstore 从未初始化为任何东西,它的大小为0 并且任何索引都超出了范围。请注意,@TheBigH 也是正确的,当您修复 addrstore 问题时,您引用了 line 的越界索引。
  • 你考虑过字符串下标超出范围的可能性吗?

标签: c++ dynamic-programming


【解决方案1】:

您永远不会初始化变量addrstore 并在程序中的任何位置为其分配一些值。这导致了一个问题。

也没有为其他任何地方的变量赋值,你怎么能像addrstore[x - 1]一样访问

【讨论】:

  • string addrstore; 和 string addrstore = ""; 都将 addrstore 初始化为完全相同的值。
  • 因此它不是 UB,但它仍然是问题
猜你喜欢
  • 2015-03-31
  • 2017-03-16
  • 1970-01-01
  • 2011-12-05
  • 2013-04-22
  • 2012-04-27
  • 1970-01-01
相关资源
最近更新 更多