Partially checked all functions, but there may be a small bug for heap allocation