Some developers are paid to make free software, because the company which hired them uses that software and wants to improve it, and doesn’t want to (or legally can’t) take it on as a completely internal project.
For example, let’s say IBM wants to use the Linux kernel. It wants to make sure Linux is high-quality and runs on IBM’s hardware, such as z Series mainframes. IBM decided that the best way to meet both of those goals is to pay people to contribute to Linux development. There are two reasons for this:
One, Linux is not public domain. The code in Linux is owned by the contributors, as a collective work, such that each contributor* owns their own input and has released it under the terms of the GNU General Public License. The GPL states that if you distribute a work licensed under the GPL, you must make the source code available to everyone you distributed it to with no further restrictions. IBM could ignore this by making a special IBM-only Linux version, to which it applies all of its patches (code modifications) and never distributes into the world. That would be a bad idea for two reasons: One, IBM wants it customers to be able to use Linux on its hardware so it needs to distribute those kernels, and, two the next reason…
*(Individual programmers in the case of hobbyists or people who are employed to contribute but did not assign their copyrights to anyone else as a term of their employment, companies in the case of people who were hired to contribute and did assign their copyrights to their employer.)
Two, IBM doesn’t want to have to keep re-applying its patches (for functionality and hardware support) to the mainline Linux kernel. That would be a massive waste of effort, because it would have to go through the codebase line by line and ensure that those patches would apply cleanly to the latest kernel version. It wants to get those patches accepted by Linus Torvalds and have the entire Linux kernel development community ensure they remain functional as the rest of the kernel changes over time. Therefore, IBM is motivated to release its code, and to play nicely with the kernel development team, because, as big as IBM is, Linus Torvalds is ultimately in charge, and Torvalds isn’t an IBM employee.
(Could IBM fork the kernel and cut Torvalds out entirely? Yes, that’s the final recourse of the Open Source/Free Software world. However, see the first point: Most Linux kernel code isn’t owned by IBM, will never be owned by IBM, and will always be under the GPL, so IBM would still have to distribute full sources to its Special IBM Linux Kernel No Linus Allowed.)
And IBM isn’t alone. A lot of companies contribute to the Linux kernel, all under the same terms as IBM. They all have perfectly reasonable profit-seeking reasons to write code which will be given away for free.