Description of a C++ Function & How It Causes a Buffer Overflow
- Functions in C and C++ behave as expected, compared to other programming languages. Functions exist, like any other variable or system information, in memory and are referenced by address. Functions, by themselves, are just blocks of code in memory that are referenced. Any error thrown by a function reference might be due to an undeclared function, or a function called incorrectly. A buffer overflow error would more likely come from the code inside the function.
- C++ is statically typed, meaning that the programmer must specify a variable type when declaring a variable. This is because C++ sets aside memory blocks of certain sizes based on the variable type. An integer (int) variable declared in a program will get a space in memory set aside specifically for an int. The memory block will be the exact size of an integer.
- Arrays are collections of variables contained in one name. For example, the array below creates a list of 10 integers, which can be accessed by referencing an index (name[0], name[1], etc.)
int name[10];
Instead of one integer, the array sets aside enough continuous space for 10. However, because array index access can be attempted on values beyond what is contained in the array (name[11], for example), errors can occur if the programmer does not watch how she uses the array. - Because of the nature of arrays in C++, an array inside a function can fall victim to buffer overflows. If a user enters a character input larger than the array can handle, the extra characters will overwrite data adjacent to the array in memory. For example,
void example(){
int login[15];
int i = 0;
while (cin >> a[i]){
i++;
}
}
The "while" loop will never end, and by the time "i" reaches 15, the user will start inputting data which overwrites memory. This can have unintended consequences, such as reassignment of a local variable, or, in specific circumstances, rewriting of function pointers to reference different, malicious code.