Added memory deallocations into code to prevent memory leaks