fix some memory leaks

NOTE: I've modified some of your code