Fixed memory leak and memory access