//* buffer overrun example *

#ifdef _MSC_VER // for MS Visual Studio compilers - to allow "classic" insecure printf and scanf #define _CRT_SECURE_NO_WARNINGS #endif #include <stdio.h> int main() { char var1[]="text one"; char var2[]="text two"; char var3[]="text three"; fprintf(stdout, "1: %s\n", var1); fprintf(stdout, "2: %s\n", var2); fprintf(stdout, "3: %s\n", var3); fprintf(stdout, "\n\n\nPlease try to enter more than %d characters ", sizeof(var2)-1);

//* 1 - uncomment only one *

// Note: gets has no way to enforce the buffer size limit and MUST NEVER be used gets(var2);

//* 2 *

// Note: fgets reads \n into the string if it fits the buffer size // fget leaves extra chars and \n unread if size is exhausted // stdin - can be used to read from the console - replace gets // fgets(var2, sizeof(var2), stdin);

//* 3 *

// Note: fscanf reads all characters untit the first whoe space // but there is no easy way to enforce the limit how much is read into the buffer // fscanf(stdin, "%s", var2);

//* 4 *

// note %ns is not enforced by the compliler, and is difficult to change on the fly // fscanf(stdin, "%5s", var2); fprintf(stdout, "1: %s\n", var1); fprintf(stdout, "2: %s\n", var2); fprintf(stdout, "3: %s\n", var3); return(0); }