Fix for the memory leak.

I must admit that i dont' fully understand your code basically because i have
had a quick look for a short time and i would have written it differently.

This should fix your leak or at least fixes it on my testbed.