-2

I got a small program which is vulnerable to buffer overflow. For example, the arrays are limited to 8 characters, but still I am able to more to it. I realized that gets() is vulnerable so I planned to use fgets(). This this function, I am getting segmentation error.

Also, other recommendations are welcome.

Thank you

#include <string.h>

int main(int argc, char *argv[]){   
int valid = 0;    
char str1[8];    
char str2[8];
printf ("Enter value for str1: ") ;

fgets(str1, sizeof(str1), stdin);  

printf ("Enter value for str2: ") ;

fgets(str2, sizeof(str2), stdin);

if (strncmp (str1, str2, 8) == 0)  
{       valid = 1;
}
printf("buffer: str1(%s), str2(%s), valid(%d)\n", str1, str2, valid);   
return 0;
}
Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
user3131067
  • 15
  • 1
  • 5

1 Answers1

2

Please reference: Why is the gets function so dangerous that it should not be used? I understand that you indicated that you already know gets is a vulnerable keyword to use in C but you still provided code for using gets...

When trying to get or store strings it is more preferable to use fgets as the format follows a buffer of space to read in strings or characters from the user: char *fgets(char *str, int n, FILE *stream).

Community
  • 1
  • 1
KillaBytes
  • 447
  • 3
  • 10