memory management improved in order to avoid seg fault