Minor fixes
Fix memory leak and segmentation fault in rare cases