Fixed potential memory leak

Fixes #1739