Patch from rob <rob@work.gb.com> to avoid freeing memory too early