BUG: Fix memory leak.

Patch is from Julian Taylor. Closes #4652.