vc ++中的运行时错误,但不是gcc中的运行时错误

时间:2017-06-24 15:07:00

标签: c++ gcc vector runtime visual-studio-2017

我有这个程序使用gcc完美运行,但在visual studio 2017中给出了“向量下标超出范围”的运行时错误。在使用调试器时,它在函数调用countWords(&v, "hello");上显示错误。我该如何解决?

#include <iostream>
#include <vector>
using namespace std;

struct Trie {
    int prefixes;
    int words;
    vector<Trie*> edges;
};

typedef Trie vertex;

void initialize(vertex *v)
{
    v->words = 0;
    v->prefixes = 0;
    v->edges.resize(26);
    for (int i = 0; i < 26; i++)
    {
        v->edges[i] = nullptr;
    }
}

void addWord(vertex* v, string word)
{
    if (word == "")
    {
        v->words++;
    }
    else
    {
        v->prefixes++;
        int k = word[0] - 'a' - 1;
        if (v->edges[k] == nullptr)
        {
            v->edges[k] = new Trie;
            initialize(v->edges[k]);
        }
        int word_len = word.length();
        addWord(v->edges[k], word.substr(1, word_len - 1));
    }
}

int countWords(vertex* v, string word)
{

    char k = word[0];
    if (word == "")
        return v->words;
    else if (v->edges[k] == nullptr)
        return 0;
    else
        return countWords(v->edges[k], word.substr(1, word.length() - 1));
}

int main()
{
    Trie v;
    initialize(&v);
    addWord(&v, "hello");
    countWords(&v, "hello");
    cin.get();
}

1 个答案:

答案 0 :(得分:3)

好吧:

int countWords(vertex* v, string word)
{

    char k = word[0];
    ...
        else if (v->edges[k] == nullptr)
    ...
        return countWords(v->edges[k], word.substr(1, word.length() - 1));
}

k等于&#39; h&#39;,这对索引名为edges的矢量无效,导致:

  

向量下标超出范围

如你所说。

h会给index 104,你的矢量大小为26,因此你肯定会超出界限,导致未定义的行为