Fix possible buffer overrun and memory leak