Fix memory leaks during encoding and decoding