bugfix for invalid memory access and memory leak