Home > OS >  Segmentation fault in c recursive function
Segmentation fault in c recursive function

Time:12-28

//void squarewall function below is showing error

void squareWall(int s) {
      static int count=0;
      if(count == s)
         return ;

      string t;
      for(int i=0;i<s;i  ){
          t = t   "* ";
      }
      cout<<t<<"\n";
      count  ;
      return squareWall(s);

}

I have written function to print square pattern of * in c using single loop and recursive call . It is giving correct output for custom cases but showing segmentation fault at the time of submission. Can someone explain what's the case here.

CodePudding user response:

Since your variable count is static, it gets declared once, after which it doesn't get assigned zero. That's why this function doesn't go into infinite recursion, but it is also why when you call your function a second time, it doesn't initialize the counter.

So, if you do something like this

squareWall(size);
squareWall(size);

the first call succeeds, but the second time, since count is still equal to size, your function immediately returns.

However, in this example

squareWall(size);
squareWall(size - 1);

the first call still succeeds, but the second call will not return to the guard clause, since count == size, s == size - 1. After that, your function will never return, so it ends up in an infinite recursion, which at some point causes the SEGFAULT.

Using static variables in recursive functions is generally not a good practice that tends to cause situations like this. A solution would be to declare count as an argument with a default value:

void squareWall(int s, int count = 0)
{
  if (count == s)
    return;

  string t;
  for (int i = 0; i < s; i  )
  {
    t = t   "* ";
  }
  
  cout << t << "\n";
  return squareWall(s, count   1);
}
  • Related