The way I understand Tor is that the "client" (say me) connects to a relay, and that relay is the only computer they connect to from then on. If that is the case, why can't a hostile relay simply run three copies of Tor modified to connect to each other, and thereby identifying me and what I am connecting to?
Don't take this as a definite answer until someone can confirm it, as I am not sure if any of these points are correct, this is all from dodgy memory
I believe that the tor client chooses all three relays it will eventually connect to.
Tor connects to the first relay, and sends a build command to it to build to a specified second relay.
The client encrypts a message to the second relays public key containing a session key for the second relay to communicate back.
The second relay replies, encrypted with the session key.
The same then happens with the third relay.
If a modded first relay tried to connect you to another second relay, it would not be able to decrypt the session key, and so wouldn't be able to communicate with the client, so the whole thing would break down.