fix off by one memory access and mem leaks