-2

what i am trying to do is asking user to enter something in format like: cd directory. Then I store "cd" in a string and "directory" in another string. Here is my code:

void main()
{
   char buf[50], cdstr[2], dirstr[50];

   printf("Enter something: ");
   fgets(buf, sizeof(buf), stdin);

   //store cd in cdstr
   strncpy(cdstr, buf, 2);
   printf("cdstr: %s(test chars)\n", cdstr);

   //store directory in dirstr
   strncpy(dirstr, buf+3, sizeof(buf)-3);
   printf("dirstr: %s(test chars)\n", dirstr);
}

The output is below with the input: cd pathname

cdstr: cdcd pathname  //incorrect answer
(test chars)          //an extra "\n"
dirstr: pathname      //correct answer
(test chars)          //an extra "\n" 

That's why?

user3368506
  • 133
  • 1
  • 8
  • Hint: look for the data type of `buf` and analyze `buf+3`. Also, check for null when using `strncpy()` – Sourav Ghosh Nov 19 '14 at 14:34
  • 1
    Because `strncpy` does not append an end-of-string character (`\0`) to the characters copied. Besides, you did not reserve room for `\0` in `cdstr`. – Ruud Helderman Nov 19 '14 at 14:34
  • As for the extra `\n`, that's because `fgets` always captures a trailing `\n`. This is all common knowledge; please take some time to study the documentation of both `strncpy` and `fgets`. – Ruud Helderman Nov 19 '14 at 14:41
  • http://stackoverflow.com/questions/1453876/why-does-strncpy-not-null-terminate – Lundin Nov 19 '14 at 14:47
  • 1
    Also please note that strncpy shouldn't be used, because it is an unsafe and mostly obsolete function. http://stackoverflow.com/questions/2114896/why-is-strlcpy-and-strlcat-considered-to-be-insecure – Lundin Nov 19 '14 at 14:48

1 Answers1

1

This is because after doing strncpy(cdstr, buf, 2), you don't have a NULL-terminated string in the cdstr char array. You can fix it by changing cdstr length to 3 and adding: cdstr[2] = '\0':

void main()
{
   char buf[50], cdstr[3], dirstr[50]={0};

   printf("Enter something: ");
   fgets(buf, sizeof(buf), stdin);

   //store cd in cdstr
   strncpy(cdstr, buf, 2);
   cdstr[2] = '\0';
   printf("cdstr: %s(test chars)\n", cdstr);

   //store directory in dirstr
   strncpy(dirstr, buf+3, sizeof(buf)-3);
   printf("dirstr: %s(test chars)\n", dirstr);
}
syntagma
  • 23,346
  • 16
  • 78
  • 134