title: Segmentation fault in a recursive function. Using std::stack (C++)
body: <p>Why am I getting a segmentation fault and how to fix it?</p>
  
  <p>I am writing the code below to sort of recursively "traverse" through a maze and find total number of paths. I am using a stack to keep track of "next step".</p>
  
  <p>ROWS and COLUMNS define the size of the maze. If I make those parameter greater than 9x9 I get a segmentation fault. I have no idea why I am getting that. </p>
  
  <p>This is the first time I've used gdb and got the following:</p>
  
  <pre><code>#3  0x0000000000400de0 in std::stack&lt;xy, std::deque&lt;xy, std::allocator&lt;xy&gt; &gt; &gt;::top (this=0x604400 &lt;buff&gt;)
  at /usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.2/../../../../include/c++/4.7.2/bits/stl_stack.h:161
  161     return c.back();
  </code></pre>
  
  <p>Leading me to believe it has something to do with my stack.</p>
  
  <p>I appreciate any help. Thanks.</p>
  
  <p>The Code:</p>
  
  <pre><code>#define ROWS 10
  #define COLUMNS 10
  
  #include&lt;iostream&gt;
  #include&lt;stack&gt;
  using namespace std;
  
  struct xy
  {
    long i;
    long j;
  };
  
  stack&lt;xy&gt; buff;
  
  long goRight (long j)
  {
    if (j &lt; COLUMNS-1)
      return 1;
    else
      return 0;
  }
  
  long goDown (long i)
  {
    if (i &lt; ROWS-1)
      return 1;  
    else
      return 0;
  }
  
  long traverse (xy POS)
  {
    long fD = goDown(POS.i);
    long fR = goRight(POS.j);
  
    xy toAdd;
  
    if (fD == 1)
      {
        toAdd.i=POS.i+1;
        toAdd.j=POS.j;
        buff.push(toAdd);
      }
  
    if (fR == 1)
      {
        toAdd.i=POS.i;
        toAdd.j=POS.j+1;
        buff.push(toAdd);
      }
  
    if(buff.empty())
      return 0;
  
    toAdd = buff.top();
    buff.pop();
  
    return (traverse(toAdd) + (fD * fR));
  }
  
  int main()
  {
    xy initial;
    initial.i=0;
    initial.j=0;
  
    cout &lt;&lt; 1 + traverse(initial);
  
    return 1;
  }
  </code></pre>