fix potential memory leak + improved error checking

PR: 1182
1 file changed