It depends on what the rental contract says.
Generally, the deposit is not intended as advance payment for the last months of the rental period, but to be refunded after the end of the rental period, minus the cost covering loss or damage, if any, for which the tenant is liable.