Buffer Overflow Demonstration
A simple bit of code demonstrating the dangers of the gets() function and how it can lead to buffer overflow vulnerabilities.
/**************************** * buffer_overflow.c * A simple little C program to demonstrate why gets() is bad * * if you enter a lot of data for 'foo', it will overwrite the data contained in 'bar' * **************************/ #include <stdio.h> #include <stdlib.h> int main(void) { char* foo = (char*)malloc(sizeof(char)); char* bar = (char*)malloc(5*sizeof(char)); *foo = 'x'; bar[0] = 'b'; bar[1] = 'a'; bar[2] = 'r'; bar[3] = '\0'; printf("foo is '%c'\n",*foo); printf("bar is '%s'\n",bar); printf("Enter new value for foo: "); gets(foo); printf("foo is '%c'\n",*foo); printf("bar is '%s'\n",bar); /* The problem with gets() is that it accepts any number of characters the user * submits and so it's possible that the user enters more characters than are * allowed within the buffer which can cause the string to extend outside of its * buffer and into other data in memory. */ //Resetting the data printf("Resetting data.\n\n"); *foo = 'x'; bar[0] = 'b'; bar[1] = 'a'; bar[2] = 'r'; bar[3] = '\0'; printf("foo is '%c'\n",*foo); printf("bar is '%s'\n",bar); printf("Enter new value for foo: "); fgets(foo, sizeof bar, stdin); printf("foo is '%c'\n",*foo); printf("bar is '%s'\n",bar); /* fgets() is a safer version of the function because with it you can restrict * gets() to only accept a fixed number of characters. */ return 0; } /* When I run the program on my PC, it takes 17 characters to overwrite the data in 'bar'. */

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Download this code in plain text format here