Fix NULL pointer  segfault
Improve memory management
Fix memory leak