fix divide by zero and memory leak