fix build error that C++ users will stumble upon
removed unused var which also caused memleak
fix weird logic, prevent memleak
fix another little memleak by making logic cleaner
fix one more little memleak and make another logic cleaner