First of all, not all crabs, shrimp, and lobsters do turn red when cooked (we added lobsters to your question because we're in Maine and you would have asked if you had known that). Second, a change in color does not exactly coincide with the little varmint being done, so in some cases, it may not be the sign you're looking for that your food is cooked (in many cases, the shellfish is done before the red is fully developed.)

The color change is quite similar to that of the leaves of most deciduous trees, where the orange and yellow colors already present in the leaves are masked by the assertive green of their chlorophyll. When the chlorophyll breaks down in the fall, the other colors become visible.

Similarly, many lobsters, crabs, and shrimp have a variety of different colors present in their shells. The pink or red color is the pigment astaxanthin, but its molecules are wrapped up in dark protein chains. So the shells are dark. Whenever you cook a protein, though, it uncoils, or denatures, and in the case of these shellfish, that frees the red pigment and the shell changes color.