Correctly allocate and free memory