fixed bug + freeing dynamic memory in functions