Fix all the bugs and functionalize!

No more leaks
Logic corrections
Add free_mem function

Signed-off-by: Evan Anderson <evan@thelinuxman.us>