Fixed memory issues.

There still seems to be a leak when throwing an exception, but as
far as I can tell, PHP is causing this and there is nothing we can
do about it.