为什么这个int会随机变成一个巨大的负值
Why does this int randomly turn into a giant negative value?
此函数运行一位,然后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)中读取,每个用户都可以有意识地或无意地阻止你的程序,并可能对整个系统造成安全漏洞。
相关文章:
- 将数字提高到一个巨大的指数
- 使用C++对一个巨大文件中的文本行进行字典式外部排序
- 如何在一个巨大的文本文件中对整数进行排序
- 在 Ubuntu(linux OS)中将一个巨大的文件读入C++向量
- 在C 中创建一个巨大的标志地图
- 我的函数总是返回一个巨大的数字
- 迭代一个巨大的 std::vector of std::vectors 并修改元素
- g++:编译一个巨大的静态std::vector
- 为什么我的程序输出一个巨大的小数
- C++程序在访问一个巨大的数组时会冻结
- 如何将一个巨大的二维数组初始化为类中的空间
- std::queue::size() 可以在 size() == 0 的 pop() 之后返回一个巨大的数字
- 使用C++解析一个巨大而复杂的CSV文件
- K的意思是有一个巨大的阵列
- 为什么这个int会随机变成一个巨大的负值
- 如何在Objective-C中包装一个巨大的静态c++库
- 在Java中使用SWIG,我如何有选择地SWIG一个巨大的C/ c++头文件的某些部分
- 内存映射一个巨大的文件在32位软件运行在64位操作系统
- 在c++中将一个巨大的文本文件(2Gb以上)分成2个块
- 计算pow(double,2)得到一个巨大的数字(C)