fix possible buffer overrun and memory leak