What C/C++ functions are most often used incorrectly and can lead to buffer overflows?

MrValdez picture MrValdez · Oct 3, 2008 · Viewed 7.1k times · Source

I've been asked to maintain a large C++ codebase full of memory leaks. While poking around, I found out that we have a lot of buffer overflows that lead to the leaks (how it got this bad, I don't ever want to know).

I've decided to removing the buffer overflows first, starting with the dangerous functions. What C/C++ functions that are most often used incorrectly and can lead to buffer overflow?

For compiler and/or tools used to help look for buffer overrun, I've created another question that deals with this

Answer

hayalci picture hayalci · Oct 3, 2008

In general, any function that does not check bounds in the arguments. A list would be

  • gets()
  • scanf()
  • strcpy()
  • strcat()

You should use size limited versions like stncpy, strncat, fgets, etc. Then be careful while giving the size limit; take into consideration the '\0' terminating the string.

Also, arrays are NOT bound checked in C or C++. The following example would cause errors. See off by one error

int foo[3];
foo[3] = WALKED_OFF_END_OF_ARRAY;

edit: Copied answers of @MrValdez , @Denton Gentry