Problem with ifstream and stack usage

closed account (10X21hU5)
Currently, I'm trying to use the following piece of code to open a file for reading and then closing it. The file name would be dof(in the first line). In the process, the file may contain commands that calls itself or others for reading, so a stack _dofileStack is created to store the previously opened file streams for later use.

From what I've been told, the following code seems to create memory leaks and some problems during recursion which results in a system freeze.

Truly need help debugging this... Many thanks in advance~

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
bool CmdParser::openDofile(const string& dof)
{
   _dofile = new ifstream(dof.c_str());

   if (!_dofile)
   {
      if (!_dofileStack.empty())
         _dofile = _dofileStack.top();
      return false;
   }

   if ((int)_dofileStack.size() <= 1024)
      _dofileStack.push(_dofile);
   else
      _dofile = _dofileStack.top();

   return true;
}

void CmdParser::closeDofile()
{
   assert(_dofile != 0);
   _dofileStack.pop();
   delete _dofile;

   if (!_dofileStack.empty())
      _dofile = _dofileStack.top();
}
Last edited on
Since you haven't posted the declaration for Cmdparser or how you're using openDoFile and CloseDoFile, I can't comment on problems related to how you're using those two functions. I can only comment on what I see in those two functions.

If your stack size > 1024 and you call openDoFile again, you're going to get unexpected results. You'll create a new ifstream (L#3), then overwrite _dofile by getting the top of stack element (L#15) effectively losing the ifstream you created.

Your stack and your _dofile pointer are going to get out of sync if you try to recurse more that 1024 levels.

Not clear what the asset is for at L#22 since you don't explicitly set _dofile to NULL in the limited code you've posted.




Also the memory leak is called because you call
_dofile = new ifstream(dof.c_str());
but never call
delete _dofile;
@Gulshan Singh - The OP calls delete when he closes the file. See L#24.
Sorry, didn't see that.
I took the screenshot.
DON'T EVER copy my homework assignment here again.
Topic archived. No new replies allowed.