为什么这个int会随机变成一个巨大的负值

Why does this int randomly turn into a giant negative value?

本文关键字:一个 巨大 int 随机 为什么      更新时间:2023-10-16

此函数运行一位,然后proc_index变量转到-18886854513。代码有问题吗?

int parse_words(vector< vector<string> > &temp_word_vec, int num_of_sub_lists)
{
    char word[MAX_WORD_LENGTH+1]; // +1 makes room for a newline character
    int proc_index = 0; //index of word arr for child process "proc_index"
    string word_str;
    cerr << "point1n";
    while(fscanf (stdin, "%s", &word) != EOF)
    {
        cerr << "point2n";
        for(int i = 0; i < MAX_WORD_LENGTH; i++)
        {
            word[i] = tolower(word[i]);
            if(word[i] == '')
            {
                word_str.push_back('n');
                word_str.push_back('');
                break;
            }
            if(isalpha(word[i]))
            {
               word_str.push_back(word[i]);
            }
        }
        cerr << "point3, proc_index = " << proc_index << ", word is " << word_str << "n";
        temp_word_vec[proc_index].push_back(word_str);
        ++proc_index;
        if(proc_index == num_of_sub_lists)
            proc_index = 0;
        word_str.clear();
    }
    return 0;
}

这几乎可以肯定是由于损坏造成的,很可能是由于您向word读取的字节数超过了为其分配的字节数。

易于检测、更改的方法:

cerr << "point2n";

至:

cerr << "point2 maxword = " << MAX_WORD_LENGTH <<
    ", strlen = " << strlen (word) << 'n';

顺便说一句,您永远不想对不完全控制的数据执行无边界*scanf("%s")。使用绑定(如"%20s"),或者,更好的是,因为您只关注字符数据,使用fgets可以防止缓冲区溢出。

或者,更好的是,使用带有getline的C++字符串,而不是一些奇怪的C/C++混合:-)

while(fscanf (stdin, "%s", &word) != EOF)

这条线有点可疑。根据您所描述的前提条件,您和fscanf都不知道word*中是否有足够的空间。你可以用简单的方法修复它:

std::string word;
while (stdin >> word)

如果性能是个问题,你可以停用与C流的同步(但你必须在两者之间消除所有C风格的IO):

const bool sync_prev = ios_base::sync_with_stdio (false);
...
ios_base::sync_with_stdio (sync_prev);

*:实际上,因为你正在从一个未初始化的流(stdin)中读取,每个用户都可以有意识地或无意地阻止你的程序,并可能对整个系统造成安全漏洞。