I am not sure how does Tor work, how safe is it as I heard that some relays are ran by bad people or government agencies.
how does Tor work
When you connect to the Tor network a Tor circuit is formed which consists of three relays (entry node, middle node and an exit node), Tor encrypts your traffic and passes it through its circuit then when your traffic reaches its destination node (outside of the Tor network) and the encryption is lifted off.
how safe is it as I heard that some relays are ran by bad people or government agencies.
Will explain that through an example:
Lets say you visit https://twitter.com/ your traffic enters the Tor network then exits at Twitter's servers and the effects are:
Twitter cannot know your real IP address or physical location.
Your internet service provider will not know that you are using Twitter, because to them you are communicating with the entry node only.
Your traffic within the Tor network is encrypted multiple times in order to prevent any eavesdropping from relay operators. But when your traffic leaves the Tor network and reaches its destination (Twitter's servers) the encryption must be lifted off so that your request can be understood by Twitter, this is why you should always use HTTPS, because HTTPS will encrypt your traffic even after leaving Tor's exit node protecting you from a bad exit that may try to read your data.
The EFF made a nice interactive web page that illustrates the usefulness of using Tor and HTTPS together.
In general everyone can operate a relay. Those can be either good or bad guys. Bad guys can do everything. This ranges from passive listening to injecting malicious content. When the main Tor people learn about those bad things they can give the Tor relay a special mark (Bad Exit flag). In this case no other client will use those relays.