V3110. Possible infinite recursion.


The analyzer detected a possible infinite recursion. It will most likely result in a stack overflow and raising a 'StackOverflow' exception.

Consider the following example. Suppose we have property 'MyProperty' and field '_myProperty' related to that property. A typo could result in the following error:

private string _myProperty;
public string MyProperty 
{
  get { return MyProperty; } // <=
  set { _myProperty = value; }
}

When specifying the value to be returned in the property accessor method, the 'MyProperty' property is accessed instead of the '_myProperty' field, which leads to an infinite recursion when getting the property value. This is what the fixed code should look like:

private string _myProperty;
public string MyProperty 
{
  get { return _myProperty; }
  set { _myProperty = value; }
}

Another example:

class Node 
{
  Node parent;
  public void Foo() 
  {
    // some code
    parent.Foo(); // <=
  }
}

It seems that the programmer intended to iterate through all the 'parent' fields but did not provide for a recursion termination condition. This issue is trickier than the previous one, as it may result not only in a stack overflow but a null dereference error as well when reaching the topmost parent entity. This is what the fixed code could look like:

class Node 
{
  Node parent;
  public void Foo() 
  {
    // some code
    if (parent != null)
      parent.Foo();
  }
}

A third example. Suppose there is a method with the 'try - catch - finally' construct.

void Foo()
{
  try
  {
    // some code;
    return;
  }
  finally
  {
    Foo(); // <=
  }
}

It seems that the programmer did not take into account that the 'finally' block would be executed both when throwing an exception inside the 'try' block and when leaving the method through the 'return' statement. The 'finally' block, therefore, will always recursively call to the 'Foo' method. To make the recursion work properly, a condition should be specified before the method call:

void Foo()
{
  try
  {
    // some code;
    return;
  }
  finally
  {
    if (condition)
      Foo();
  }
}


Do you make errors in the code?

Check your code
with PVS-Studio

Static code analysis
for C, C++, and C#

goto PVS-Studio;
We use cookies for the analysis of events to improve our content and make user interaction more convenient. By continuing the view of our web-pages you accept the terms of using these files. You can find out more about cookie-files and privacy policy or close the notification, by clicking on the button. Learn More →
Do not show again