My colleagues have answered your question below. Check your lease agreement to see if there is any clause or verbage in there regarding the validity of your lease in the event the home sells. Also, check to see what your rights are while the home is on the market, there is likely verbage stating that you will allow access to the home for showings within "x" amount of time of the lease expiration.
It is likely that the home will be marketed with the information that the new owner will be required to honor your lease until end of term.
Yes, it's legal.
Why would someone want to sell a rented property:
--Maybe it's not "making money." Maybe the mortgage is, say, $1,800, and the renter is only paying $1,600. That's $200 negative cash flow right there. When you factor in repairs, potential vacancies, etc., it's probably closer to $400 a month negative.
--Maybe the owner needs the money. Suppose the house is worth $300,000 and the owner owes $200,000. Maybe the owner has some medical expenses. Or needs money for a child's school tuition. If he sells, he'll get (after commissions and other things) maybe $70,000 in cash. That may meet his needs a lot more than getting a couple hundred dollars a month in positive cash flow.
--Maybe the owner has a better investment possibility. Maybe the owner is getting an 8% return on investment. Now he has the opportunity to make a 12% return. That's a 50% increase (from 8% to 12%).
--Maybe the owner is retiring. Or at least tired of managing rentals.
In other words, there are lots of reasons. But the real point is: For whatever reason, your landlord has decided to sell.
The good news is that generally your lease carries over to the new owner. Certainly check your lease to make sure there isn't something in there saying otherwise. But generally a valid lease remains valid and binding on both the tenant and the [new] owner. Now, either your current landlord or the new owner may want you to move. They may even offer you money to move . . . which you can take, if you feel like it. But likely you're in the driver's seat if you want to keep renting there through the end of your lease.
Hope taht helps.