code refactoring and fixed valgrind errors
useless allocations avoided