strncpy function does not work properly

840 views Asked by At

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?

1

There are 1 answers

2
syntagma On BEST ANSWER

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);
}