Fixed memory allocation

Added calls to free for each call to malloc