use RAII to manage resources, simplify and remove malloc/free