October, 04, 2019
A buffer, in terms of a program in execution, can be thought of as a region of computer’s main memory that has certain boundaries in context with the program variable that references this memory.
The above line will declare an array of 10 characters in C. Here buff is the left boundary and buff is the right boundary of the buffer.
Now that we have seen the idea of a buffer, we can talk about what is meant by buffer overflow.
A buffer is said to be overflown when the data (meant to be written into memory buffer) gets written past the left or the right boundary of the buffer. This way the data gets written to a portion of memory which does not belong to the program variable that references the buffer.
Note : Though in the above case we have taken the example of a character array as a buffer, we can have buffer overflow with different types of data structures as well such as stack, linked lists, etc if we violate their boundary conditions.
buff = ‘a’;
The effect of the above code will be that most likely during runtime, your code will throw a Segmentation Fault or Stack Smashing Error.
This is due to buffer overflow.
buff[-1] = ‘a’;
This code will also throw the same kind of array index violation errors.
In general accessing a memory location that has not been assigned for your program can lead to buffer overflow.
Hence, de-referencing dangling pointers, filling array or string with more elements than it is defined to, etc can all lead to a buffer overflow and hence segfault.
More Examples :
char a = “This string is longer than the buffer can hold”;
int *a = (int *)malloc(10 * sizeof(int)) ;
a = 100 ;
Buffer overflows are one of the most common and also one of the most notorious errors in programming as they can lead to overwriting of memory and also unexpected program crashes.
The ‘Segmentation Fault’ error is the most common type of error associated with buffer overflow.
There can also be cases where buffer overflow does not give errors immediately. But what happens in these cases is that the program will secretly overwrite neighboring memory allocated to other programs/same program and eventually will lead to a crash.
Example of a segfault crash :<br>
Special Note for C Programmers :
C Programmers need to be extra careful when writing code to take care of buffer overflow because many C functions do have the feature of boundary checking and hence the slightest mistake can lead to a segfault easily.
Also since it allows pointer and low level memory manipulation, it is the programmers duty to check for buffer overflow.
Thank You !
Share this post:
Redis delivers sub-millisecond response times enabling millions of requests per second for real-time applications in Gaming, Ad-Tech, Financial Services, Healthcare, and IoT....