Fix several memory leaks, don't rely on power function in math.h
Fix tests