Storing Data Into a Buffer Without Performing Bounds Checking


Definitions:
 

Buffer Overflow - When a program writes beyond the bounds of a buffer

Bounds Checking - Setting or verfiying the size of data before storing the data into a buffer
 

What You Should Not Do
 

Read data into a finite length buffer without doing any sort of bounds checking. This can lead to a buffer overflow if it writes past the end of the buffer which can overwrite program data, cause indeterminate program behavior (usually leading to a segfault), or hijack the program's flow.
char buffer[1024];              //initialize a buffer of size 1024
int i = 0;
char c;
while((c = getchar()) != '\n')  //read in characters until newline character
{
    if (c == EOF)
        break;                  //exit the loop
    buffer[i++] = c;            //store read characters into buffer
}


The preceeding code has the potential for buffer overflow if the source of characters has a size greater than 1024 because the while loop portion of the code reads in characters without checking if the end of the buffer has been exceeded.
 

What You Should Do
 

ALWAYS check the bounds of data stored in buffers. To make the above example safe, stop at the end of the buffer:
char buffer[1024];
int i = 0;
char c;
while(((c = getchar()) != '\n') && (i < 1024)) // read to the end of the line or
                                               // until the buffer is full
{
    if (c == EOF)
        break;
    buffer[i++] = c;
}

Or with a for loop: char buffer[1024];
int i;
char c;
for(i=0; ((c = getchar()) != '\n') && (c != EOF) && (i < 1024); i++)
{
  buffer[i] = c;
}

 

Most standard library functions in C do not do bounds checking , including strcpy(), strcat(), sprintf(), scanf(), etc.
 

Concept Map
 

This example refers to the point G (Control the input values when possible by limiting them to a finite set), which comes under category of "Input Validation" and "Assumption". In this case, we should not make the assumption that the user will enter input within the buffer limit of 1024. Therefore, validating the input length is important to prevent buffer overflow.
 

 

 

 

JSN Teki template designed by JoomlaShine.com