fix memory allocation, still have some bugs