/****************************
 * 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'. */