fix potential leaked handles and buffers