【发布时间】:2014-02-11 15:59:44
【问题描述】:
我正在为一个大文件编写解析器,我负责从输入文件读取的函数之一有一个名为 peek 的字符缓冲区。基本上,当main 反复调用这个函数时,peek 最终会被一些奇数覆盖。这是main 调用的函数。 bufferAsInt:
void bufferAsInt(ifstream &inf, int &i)
{
char peek[3];
inf.read(peek, 3);
i = atoi(peek);
//I'm not using the >> operator to read an int because the int is just
//3 chars long in the input file and two consecutive integer values can
//be written like this: 123456 for 123 and 456.
}
我发现当我将这些值写入输出文件时,当读取一个只有两位数长的 int 值时,第三位数字(或其他数字)将留在 char 缓冲区peek 和值会被错误地写入输出文件(这只发生在从输入文件中读取大量数据之后。)所以经过数万次迭代,当读取像15这样的数字时,会得到的值写入我的输出文件可能类似于156。
为了解决这个问题,我将bufferAsInt 的实现更改为:
void bufferAsInt(ifstream &inf, int &i)
{
char *peek = new char[3];
inf.read(peek, 3);
i = atoi(peek);
delete [] peek;
}
(当然我是在猜测问题所在)。我想知道的是,如果我的问题已解决这一事实是在堆上声明此 char 缓冲区的某种奇怪结果,或者问题实际上是我的程序用完了堆栈内存。
我的计算机中有 6GB 的 RAM,并且在运行时,据我所知,没有其他程序会使用足够的内存来导致此问题。
【问题讨论】:
-
谁调用 bufferAsInt ?下一个怎么称呼?
-
即使您有 6GB 的 RAM,堆栈也可能只有几 MB。
标签: c++ memory heap-memory stack-memory