It's legal to sell your program if it doesn't infringe any law or anyone else's intellectual property. Examples of things that can get you into trouble:
statutes: Some countries have export laws that forbid you to distribute certain types of encryption without proper export controls.
patents: If you use a design or invention that is under patent protection you could be liable for infringing patent rights.
trademark: If you improperly use a trademarked name you could be subject to damages.
licensing: If you violate a license to which you have agreed you can be sued for damages.
copyright: If you appear to have copied something without license you can be liable for damages.
Just because: If someone wants to sue you, they can.
Since there's no way to guarantee your business won't run into liability from infringement – or from some other failure – people normally conduct business through entities like LLCs that shield them from personal liability. Depending on their concerns and finances, they may also: