fix leaks and int overflow