My question is, what is the difference between these two pieces of code.
1)
#include <stdio.h>
#include <stdlib.h>
#define SIZE 7
int main()
{
int strSize;
char tim[SIZE];
printf("Enter the time (format xx:yy)= ");
// for example when I type 14:45
gets(tim);
int i;
for (i=0; tim[i] != '\0'; i++)
{
}
strSize=i;
// result of program turns as 5.
printf("%d", strSize);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#define SIZE 7
int main()
{
int strSize;
char tim[SIZE];
printf("Enter the time (format xx:yy)= ");
// when I type again 14:45
fgets(tim, SIZE, stdin);
int i;
for (i=0; tim[i] != '\0'; i++)
{
}
strSize=i;
// result turns as 6
printf("%d", strSize);
return 0;
}
I also use strlen to see if there is really a difference between these two methods. And strlen also give different values.
The TL;DR; answer is that
fgets()includes asizeparameter (it reads up to n-1 characters) whereasgets()is unconstrained by size.This makes any system using
gets()vulnerable to buffer-overflow, simply by entering too many characters.As such
gets()should NEVER BE USED - to reinforce this, ISO/IEC JTC1/SC22/WG14 (the custodians of the C standard) have removed this function from the standard!Example (for your
tim[7]) and "The cat sat on the mat":gets()returns "The cat sat on the mat\0", overwriting the next block of memory (or stack)fgets()returns "The ca\0".