When Jesus told Peter “whatever you bind or loose on earth is bound or loosed in heaven” (Matt. 16:18-19), He was promising to protect Peter from teaching error to the universal Church. Otherwise, Jesus could not make such a sweeping promise to Peter. Because God cannot lie (Titus 1:2; Heb. 6:18), Peter must be protected from teaching error, since what he binds or looses, heaven binds and looses as well. Indeed, God intrudes into the mind of the pope and prevents him from teaching error, just like the Father penetrated the mind of Peter when he confessed that Jesus was the Christ.
You recall what happened next. Jesus said Peter is the rock upon which He would build the Church and gave Peter the keys to the kingdom of heaven. The basis for infallibility is the ability of the pope to accept and confess God’s divine guidance without error. It has nothing to do with the pope’s private opinions or conduct. The fact that all the popes have spoken with one voice over the past 2,000 years when it comes to dogmatizing principles of Catholic faith and morals proves that Jesus has kept His promise.
Note also that nothing the Church teaches on faith or morals just “pops up.” This is because the Church’s teaching comes from the Tradition of the apostles, which we call the sacred deposit of faith. The Church may try to clarifying the way she expresses doctrine, but there can be nothing new under the sun, as they say. Often, the Church will issue a dogmatic teaching to clarify a point of contention or refute a heresy. But clarifying the way in which she expresses the divine deposit of faith does not mean she makes up new doctrines. The doctrines remain the same.