Criminal/Detective "Confessions": Real or Literary Device?

It’s very common for fictional depictions of crime/detective situations for the criminals, having captured the heroes and planning to kill them, to confess to their crimes and explain how they pulled off their various capers. Of course, the detectives/heroes are saved at the last minute, and capture the criminals, and the confessions are used against them, whether in court or in crushing their operations.

It happens the other way around as well, with the hero/detectives explaining to the captured criminals how they cleverly foiled their plots, although in these cases it generally does not rebound against them.

Question is whether these have a basis in reality. Is there some human instinct to lord it over one’s vanquished foes which motivates people in these situations to communicate the details to their adversaries specifically? Or is it purely a literary or plot device, to enable the hero to comprehensively solve the case and/or to enable the author to communicate the details to the reader/viewer?

As you might expect, there’s a TV tropes page for this:

It doesn’t list any real life examples.