1

I know that I can use gets(char *) to get string input from user with spaces included but I read that buffer overflow problem. Using strcpy, strcmp (and a few other functions) is not safe we should use strncpy, strncmp and explicitly mention the size of the input. Some guy on Stack Overflow told me that. So, I am worried about using gets for getting input from user or it's safe? If it's safe tell me I'll continue using it. If not then what is the other way getting spaced string input from user safely?

#include <stdio.h> 
#include <stdlib.h> 

int main()
{
  char *a[2]; 

  char b[] = "first";
  char c[] = "second"; 

  int s1; //,s2;

 // printf("\nLong you want your %s string to be: \n",b);
 //scanf("%d",&s1); fflush(stdin);

 //printf("\nLong you want your %s string to be: \n",c);
 // scanf("%d",&s1); fflush(stdin);

  int i;
  for(i=0; i<2; i++) {
    printf("\nLong you want your %s string to be: \n",b);
    scanf("%d",&s1);  fflush(stdin); 
    a[i] = (char *) malloc(s1*sizeof(char)); 
  }

  printf("\nEnter the first string: \n");
  scanf("%s", a[0]); fflush(stdin);

  printf("\nEnter the second string: \n");
  scanf("%s", a[1]); fflush(stdin);

  printf("\nThe first string is: %s\n", a[0]);
  printf("\nThe second string is: %s\n", a[1]);
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    This question appears to be off-topic because it shows a lack of research. – Code-Apprentice Sep 07 '14 at 19:50
  • See http://stackoverflow.com/questions/4309746/safe-alternative-to-gets – Code-Apprentice Sep 07 '14 at 19:53
  • Note that it is as easy to abuse `strncpy()` and (especially) `strncat()` as it is to abuse `strcpy()` and `strcat()`. Using `strncmp()` vs `strcmp()` is normally a question of the required logic rather than safety — they're readonly operations. If you don't know whether your data is in null-terminated strings, nothing is safe. Ultimately, if you don't know the length of the strings you're copying, they're not safe either. Using `gets()` is never safe; it is no longer a part of Standard C and should never be used. – Jonathan Leffler Sep 07 '14 at 20:52

1 Answers1

-3

Please do some research.. this http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1044652485&id=1043284385 may help you.

µtex
  • 900
  • 5
  • 12