You may have noticed that train tracks always seem to have crushed rocks between them. Those rocks actually have a name. They're called ballast, and they're not just an aesthetic choice. They serve a purpose.
Their use is to hold the wooden cross ties in place, which in turn hold the rails in place. Think about the damage train tracks face being left exposed to the elements. Especially if they're in Arizona.
When trains do ride over the tracks, it can cause its own set of complications. A Union Pacific Big Boy locomotive and its cargo can weigh up to 1,200,000 pounds. The rails are meant to withstand that weight, but another issue comes from it.
These beams are often made of hardwood and impregnated with creosote for weather protection. Next, the steel rails are laid over top of them. They are attached with clips or anchors that hold them down but allow them to move longitudinally as they contract or expand. They move, but in a way that won't shift the tracks.