Fix some bugs which may lead to crash