It happens when someone replaces the tub spout, and doesn't want to risk removing and replacing the nipple in the wall with the correctly sized one.
The fix is to remove the spout and the nipple from the wall (the short pipe threaded on both ends) and get a new nipple of the correct length. Before removing the spout, measure the gap so you know how much shorter the new nipple needs to be. Premade nipples will be sold in 1" or 1/2" increments, but some stores can cut them to a specific length if you end up needing something like 4-3/4" or something.
Use plenty of WD-40 or thread penetrator on the nipple threads in the wall before attempting to remove it. That galvanized pipe can get rusty, and can be hard to remove (probably why the last people didn't attempt it).