Fixed a reference counting bug that could lead to double free errors.