I have heard plenty about buffer overflow errors: that they can allow malicious code to be run on a machine; however, I cannot find why or how it does this. What exactly happens during a buffer overflow, and how does it allow someone to run their code on a machine?

This is C related as I hear C has alot of problems with this, and I was wondering how to make sure you do not leave room for a buffer overflow error in your code.