make memory deallocation consistent and fix array bounds mismatches