Fix some bugs which would cause crash