Create generic malloc freeing method to reduce repetition.