A home is sold when the deed is transferred.
If it doesn't pass inspection, look to your contract. Language varies, but hopefully you had an inspection contingency in yours. Your Realtor can explain how it'll work in your area. In some cases, you can cancel the contract. In most cases, the seller has the option of offering to have the repairs done--or to set money aside in escrow so that you can do it.
An inspection is done before closing, when the property is still owned by the seller.
Hope that helps.