The medullary cavity is the central cavity of bone shafts where red and yellow bone marrow is stored, playing a crucial role in the production of blood cells and fat storage. It is surrounded by compact bone, providing structural support and protection to the marrow within.