fix heap buffer overflow and socket remove on error