What does the punishment of the grave mean?
The grave here does not mean the pit in which the body lies, but the state of the soul between death and resurrection. In that state the soul already senses whether it is healthy or sick, and it feels peace or pain.
In their prayers Muslims seek protection from the punishment of hell and also from the punishment of the grave, as the hadith above shows. So there are two different stages. One follows death, the other follows the resurrection.
The grave here cannot mean the earthly grave. Graves are sometimes opened, because of building work, heavy rain or natural events. No one has ever seen any punishment or reward there. Many people have no grave at all. What is meant is a state of the soul after death, which the first verse above describes as a barrier until the day of resurrection.
This state can be compared to a child in the womb. The child already has some awareness, but it is very faint. If it is unwell, it suffers, and the mother feels that suffering too. If it is healthy and moves about lively, the mother is happy. In the same way the soul continues to develop after death, until at the resurrection it is, as it were, born anew.
During this time the soul senses its own condition. If it did good in life, it is healthy and feels peace. If it made itself sick through evil deeds, it suffers. That is the punishment of the grave.
The full reality of this state is beyond our imagination. What matters is the idea behind it. What we make of our soul in this life stays with us beyond death.