Buffer overflow occurs when too much data is inserted into a buffer than it can handle, which may lead to arbitrary code execution if a memory pointer is overwritten. The document provides an example of a buffer overflow happening when user input longer than the buffer size is read using gets() into the buffer without limits. To prevent this, fgets() should be used instead, as it allows specifying the maximum number of characters to read from input.