Monthly Archives: October 2010

PHP Memory Leak when Throwing/Catching and Recursing

I spent the better part of the day chasing down this bug, so maybe Google in its infinite wisdom will help speed up your search for the same bug. It’s really an obvious and simple solution, but all the tough problems are like that, aren’t they?

The Situation

I am retrieving and manipulating binary trees of objects. Typically I can handle objects 9 levels deep without bumping into the PHP memory limit on our server (128MB), but occasionally an exceptionally large object will come up and my script will crash. To handle this, I set up some try/catch blocks. They notice when there are just 16MB left and throw an Almost out of memory error. That error is caught and the request is made again at 1/2 the original depth down to two levels deep (so really 9, 4, 2).You can see how I do this, with memory_get_usage(), in the code snippet below.

The Throw

 // Assumes memory limit is in M (eg. 128M)
 // 1048576 bytes per MB
 if((str_replace('M','',ini_get('memory_limit'))*1048576) - memory_get_usage() < 1048576*16){ // 16 MB headroom
    unset( -- all my vars go here to get unset --);
    throw new Exception("Almost out of memory");
 }

ini_get returns whatever is in your php.ini file (or possibly your .htaccess file). I turn that into bytes since that’s what memory_get_usage returns, and then verifies that it’s less than my decided max headroom.

The Catch : Broken

function getLevels($start_idx,$levels = 9){
   try {
            return $this->getBinaryTree($levels);
        } catch (Exception $e) {
            switch($e->getMessage()){
            case "Almost out of memory":
               $max_tree_depth = (int)($levels/2);
               if($max_tree_depth >= 2){
                    return $this->getLevels($start_idx,$max_tree_depth);
               }else {
                    throw new Exception("Out of memory even after getting tree with 2 levels");
               }
               break;
            default:
               throw $e;
         }
     }
}

The Problem

Since the Throw block was unsetting all the variables before actually throwing the error, I expected that the only overhead for this process would be the typical overhead associated with recursive calls. A whole bunch of debug and memory_get_usage() statements later I confirmed that this was not the case, and that my program was still crashing with the Out of memory even after getting tree with 2 levels error.

The Solution

After many fruitless paths, Google led me to this thread in a C/C++ forum where I read the phrase

an exception object is being created and

AH HA! An Exception OBJECT! I always knew that exceptions were objects. I knew that you could call methods on them, etc. but somehow it never occurred to me that they would take up memory and need to be freed up like any other object! All I had to do was unset the caught object before recursing and all was well once again.

The Catch : Fixed

function getLevels($start_idx,$levels = 9){
   try {
            return $this->getBinaryTree($levels);
        } catch (Exception $e) {
            switch($e->getMessage()){
            case "Almost out of memory":
               $max_tree_depth = (int)($levels/2);
               if($max_tree_depth >= 2){
                    unset $e; // <------------------------ RIGHT HERE!
                    return $this->getLevels($start_idx,$max_tree_depth);
               }else{
                    throw new Exception("Out of memory even after getting tree with 2 levels");
               }
               break;
            default:
               throw $e;
         }
     }
}

Summary

It was a shameful noobie mistake that I’m happy to share. In summary, Exceptions are objects, and if you don’t unset them when using recursion in your try/catch blocks, you might think you have a memory leak.

Best of luck!

Posted in Programming, Projects | Tagged , , , , , , , , | Leave a comment

Does Anyone Have a Place I Could Turkey Hunt?

This is a long shot, but I am looking for a place to go turkey hunting in Minnesota, on October 30th. If any of my friendly blog readers happen to have a place we could go, I would be very grateful.

Who Would Be Hunting?

It would just be me and my brother in law. We are both Eagle Scouts and we are both respectful of nature and your land. We don’t drink or litter. Both of us have been hunting before (but not for turkeys) and feel strongly about gun safety.

If you are offering a place for us to hunt we would be happy to have you along too, of course!

Where Do We Want To Hunt?

We would be happy to hunt anywhere that a turkey permit is still available, To see which areas still have available licenses, you can check this chart: http://www.dnr.state.mn.us/licenses/lotteries/turkey_fall.html. To see what area you live in, you can check this map (warning, large PDF): http://files.dnr.state.mn.us/rlp/regulations/hunting/2010/deermap.pdf. We do both live in area 601 (greater metro area),but would be happy to travel a bit in order to get to hunt!

Thank You!

You can leave a comment here, email me at [email protected] or call me by clicking this button:

Posted in Something Interesting | Tagged , | Leave a comment

Rocket Planning, First Steps

I’m building Ryan a rocket from scratch. The first step was to decide on an engine since the size and weight of the rocket would need to be built around that.

D12-5, I Choose You!

I chose the Estes D12-5 rocket engines and bought 3 of them from Amazon.

I chose the D engines as a compromise between price and power as well as for convenience. The first letter of the rocket engine name describes how powerful it is. E is more powerful than D which is more powerful than C. C engines cost about $3.00 per engine, D engines are just under $5.00 each and E engines are almost $10 each. $10 per launch seemed too expensive and the fact the D engine supposedly fits nicely inside a piece of PVC pipe sealed the deal.

The next step was to figure out the parameters I had to use to build the rocket. I didn’t want to build a cool rocket and have it only launch 10 feet off the ground.

How High Can I Fly?

I found a fantastic site with all the formulas I needed to calculate how high my rocket would go. My physics skills are rusty, but I can still plug-and-chug formulas like nobody’s business.

I put all the formulas into a spreadsheet which you can download here. You need to enter 6 fields, and it should tell you how high your rocket will go. The fields you’ll need are

  • The Mass of Your Rocket in Kg
  • The Mass of Your Motor in Kg
  • The Mass of the Motor Propellant
  • The Diameter of your Rocket in cm
  • Your Motor Impulse In Newtons*s^2
  • Your Motor Thrust in Newtons

Before you panic since you don’t know those values, they’re pretty easy to look up. A chart on the same site lists the blue italicized values above for Estes motors – other companies provide this information too. Your motor’s thrust (the red bold value) is the first number in its name, eg, the 12 in D12-5.

The two remaining values are the ones I was looking for. Essentially I end up with three unknowns. My rocket’s mass and diameter, and how high it will fly. By playing with the two inputs I can see what the effect will be on the height.

Fun Vs. Safety

Raygun Retro Rocket
Raygun Retro Rocket

I stumbled across the NAR Model Rocket Safety Code while looking up engine info and realized that rule number 1 conflicts with my plan:

Materials. I will use only lightweight, non-metal parts for the nose, body, and fins of my rocket.

I want to build a retro rocket similar to the one picture at left. I am considering using thin aluminum sheets and pop-rivets, both of which are metal, of course.

I guess silver spraypaint would get a similar look but I am kind of hoping that I can build a rocket sturdy enough that the kids can play with it as a toy when it’s not being launched. I’m not convinced that I can accomplish that with cardboard and plastic.

Now, off to the hardware store!

Posted in Something Interesting | 2 Comments