So have you heard of the function gets
- char *gets(
-
char *buffer
-
);
returns a string from the keyboard, but it does not put a check on the length of the string. Try this program
- #include <stdio.h>
-
-
int main(int, char *[])
-
{
-
char hw1[] = "Hello World!";
-
char input[5];
-
char hw2[] = "Hello World!";
-
-
gets(input);
-
-
puts(hw1);
-
puts(input);
-
puts(hw2);
-
-
return 0;
-
}
when it runs you have to input data, first time you run it just enter 2 or 3 characters, it will appear to work. Then run it again and input more characters and keep going inputting more and more.
Various things will happen depending on your platform and compiler options but what you might see is that with 2 or 3 characters it appears to work, with a few more the hw1 and/or hw2 strings get over written and with a lot more the program crashes.
This is a buffer overrun error (an exploit often used by hackers if left in code) the gets function does not stop you writing more string to the pointer it receives than there is room for so when you input 10 characters (say) it just merrily stamps over the data around the input variable.
Step forward the fgets function
- char *fgets(
-
char *str,
-
int n,
-
FILE *stream
-
);
This function takes a length of buffer as well as a pointer, it guarantees not to write more data to the pointer than you tell it is available via the parameter n.
But it takes a FILE * surely it works on a file input stream? Well yes it does however the standard input, standard output and standard error are file streams and can be accessed as such. You don't have to open them they are automatically opened for you all you have to do is use their identifiers
stdin - for standard input - input stream
stdout - for standard output - output stream
stderr - for standard error - output stream
declared in stdio.h. Modifying the code to use fgets it becomes
- #include <stdio.h>
-
-
int main(int, char *[])
-
{
-
char hw1[] = "Hello World!";
-
char input[5];
-
char hw2[] = "Hello World!";
-
-
fgets(input, sizeof input, stdin);
-
-
puts(hw1);
-
puts(input);
-
puts(hw2);
-
-
return 0;
-
}
Now when you run the program it does not matter how much data you input, not more than 5 characters (the last one being '\0') are written to input and the program does not crash.