Search code examples
cstringstrncpy

Why strncpy() is not respecting the given size_t n which is 10 in temp2?


This problem is blowing my mind...Can anyone please sort out the problem because i have already wasted hours on this.. ;(

#include <stdio.h>
#include <string.h>
int main(){

  char string[] = "Iam pretty much big string.";
  char temp1[50];
  char temp2[10];

  // strcpy() and strncpy()
   strcpy(temp1, string);
   printf("%s\n", temp1);

  strncpy(temp2, temp1, 10);
  printf("%s\n", temp2);
  return 0;
}

Result

Iam pretty much big string.
Iam prettyIam pretty much big string.

Expected Result:

Iam pretty much big string.
Iam pretty

Solution

  • The strncpy function is respecting the 10 byte limit you're giving it.

    It copies the first 10 bytes from string to temp2. None of those 10 bytes is a null byte, and the size of temp2 is 10, so there are no null bytes in temp2. When you then pass temp2 to printf, it reads past the end of the array invoking undefined behavior.

    You would need to set the size given to strncpy to the array size - 1, then manually add the null byte to the end.

    strncpy(temp2, temp1, sizeof(temp2)-1);
    temp2[sizeof(temp2)-1] = 0;