Fix buffer overflow and a leak