Improving memory management (allocation/free)

Far from perfect yet relying on valgrind, but I will see that later.