backport from trunk (rev #9757)
- fixed double free
  Thanks to Pete Kelly for reporting and helping with troubleshooting
- removed unused variable