Red giant stars have a lot of gravity pulling them inward. Normally they don’t collapse inward because the nuclear fusion going on inside them pushes energy outward. That balances the pull of gravity. When the nuclear fusion stops, the force of gravity pulls the star inward. Then when the inner shell hits the iron core, it makes a huge shock wave and the star explodes.
When a star explodes, it shoots out billions of atoms into space. In space, the atoms form a huge cloud of dust called a nebula. Other than hydrogen and helium, pretty much all of the atoms that are around today originally formed inside stars. Then they shot out into space when their star became a supernova. Most of the carbon, oxygen, nitrogen, silicon, and iron that we have on Earth originally came from a supernova explosion. In addition, because the explosions are so hot (hundreds of millions of degrees), new, heavier kinds of elements, like gold and uranium, form within the explosion itself. That’s why gold and uranium are rare. They only form during supernova explosions.
The first stars became supernovas about 14 billion years ago. But stars are still going supernova today, whenever they run out of fuel. In 1054 AD, astronomers in China and the Islamic Empire recorded a supernova. They noticed a star so bright you could see it in the daylight. That supernova is now the Crab Nebula. Our own star, the Sun, will never become a supernova because it is not big enough to make enough gravity. Instead, billions of years from now it will become a white dwarf.