fix double free bug

Addresses #340.
Merge pull request #402 from satta/segfault

fix double free bug