Schmalls » Blog » 2008 » February 2008 » Infinite Recursion (i.e. Hard To Spot Error)

Infinite Recursion (i.e. Hard To Spot Error)

I ran into a hard to spot bug the other day and decided to share it. I worked on some code for a while and then fired up my browser to test it. I would be using Xdebug straight from Eclipse PDT, but I can't get it to work with the latest php snapshots for Windows. Anyway, when I went to test it, there was no output. It turns out that php-cgi had segfaulted. I spent the better half of a day trying to figure out the problem. When I thought I had figured it out, I would try to write up a test script for just that problem, and all of them ran just fine. Just when I was about to give up, I found the problem in this little class I was sure couldn't be wrong.

It is the base class for a graph edge. All the class does is constructs an object with references to its two vertices with a function to retrieve each. And here is the code (comments removed):

class Edge
{
    private $firstVertex;
 
    private $secondVertex;
 
    public function __construct( & $first_vertex, & $second_vertex )
    {
        $this->firstVertex = & $first_vertex;
        $this->secondVertex = & $second_vertex;
    }
 
    public function firstVertex()
    {
        return $this->firstVertex;
    }
 
    public function secondVertex()
    {
        return $this->secondVertex();
    }
}

The problem was in the last function. Instead of returning the private variable value, I called the function recursively. Since this is infinite recursion, the PHP interpreter will eventually crash (in under a second in most of my cases) and not output anything. At first, I thought this would be a bug, but these bogus bug reports say that it is the expected behavior. I wish I could get Xdebug working to catch something like this (one of the bug reports say it would). So if anyone knows how to get Xdebug working on Windows with the latest PHP snapshots, let me know.

Discussion

Enter your comment
JMDGP
 
blog/2008/02/infinite-recursion-ie-hard-to-spot-error.txt · Last modified: 2009-09-20 00:00 by Josh Thompson