code converges, but doesn't give right answer. Possible memory allocation issues