我正在使用以下功能来读取文件。

void read_file(){
   char buf[BUF_SIZE];
   // file is a vraiable defined and assigned during initialization
   int numread = pread(file->fd, buf, BUF_SIZE, file->curpos);
   // other logic follows
   file->buffer += buf;
}


仍在同一类中的以下函数评估从文件读取的缓冲区的内容。

void evaluate(){
   read_file();
   //evaluate the file->buffer contents
}


根据我的理解,当函数退出时,堆栈变量会自动“删除”,但我似乎无法理解为什么在连续调用evauluate()时未清除read_file()函数中的buf变量。

例如,如果我这样做;

int main(){
   evaluate(); // first call works as expected
   evaluate(); // second call buf variable still has contents from previous call
   return 0;
}


我希望能向您指出解决此问题的正确方向。提前致谢。

最佳答案

无论值多少钱,都不必清理释放的内存。释放并重新获取它后,其内容状态将变为“不确定”。换句话说,它可能包含上次运行的数据,但是绝对没有必要。你不能依靠这个。

如果您感到困惑,建议您对缓冲区进行零初始化:

char buf[SIZE] = {};


您可以查看this question

关于c++ - 堆栈数组变量清除,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48186784/

10-11 22:51
查看更多