The very centre of our religion is why God punished the innocent, Jesus, for the guilty, us.
God in the Old Testament would periodically punish children along with their parents and wives with their husbands. But have a bigger picture, God permits the death of countless babies in history. Evil is not only done to evil people. Not just evil people die. We all die.
In the specific case of God causing King David's child to die, God used the fact of a child's death to punish its parent and force that parent to repentance, especially of the murder he committed when he heard the child's mother was pregnant with his child. God's own child would one day also be killed in order to gain King David grace from that repentance.
God kills everyone and God will kill you. Death is a certainty, life is a gift.