fix malloc leak and add some pointer magic