Skip site navigation (1)Skip section navigation (2)

FreeBSD Manual Pages

  
 
  

home | help
Strn(3) 		    Library Functions Manual			 Strn(3)

NAME
     Strncpy(), Strncat() - Safe string copying functions

SYNOPSIS
     cc -I/usr/src/include . . . -L/usr/src/lib -lStrn

     #include <string.h>
     #include <Strn.h>

     char *Strncpy(char *dst, char *src, size_t max);

     char *Strncat(char *dst, char *src, size_t max);

DESCRIPTION
     The  Strn	library provides bounds-safe versions of string copying and con-
     catenation functions.  These are useful with fixed length character  arrays
     because  the functions will not overwrite past the end of the array, unlike
     strcat or strncat.  The functions also guarantee that a string is	nul-ter-
     minated, unlike strncpy or strncat.

     For example:

	  char bar1[8], foo[8], bar2[8];

     In  the  following  block,  Strncpy correctly sets this to "hello w", using
     seven characters + a nul terminator, so the array is  full  and  nul-termi-
     nated.

	  Strncpy(foo, "hello world", sizeof(foo));

     strncpy  will write 8 characters, but it won't nul-terminate.  If you tried
     to print "foo" you would get "hello wo" and garbage.

	  strncpy(foo, "hello world", sizeof(foo));

     These cooperate to guarantee that the bounds of  "foo"  are  not  violated.
     Here, you would get "hello" and then "hello w".

	  Strncpy(foo, "hello", sizeof(foo));
	  Strncat(foo, " world", sizeof(foo));

     These  two  would	overflow,  with this usage.  The strncpy would work, but
     then the strncat would happily write past the end of foo.

	  strncpy(foo, "hello", sizeof(foo));
	  strncat(foo, " world", sizeof(foo));

     To get the result I want, I would have to do this, which with all the extra
     overhead in the third argument is unacceptable.

	  strncpy(foo, "hello", sizeof(foo));
	  strncat(foo, " world", sizeof(foo) - strlen(foo) - 1);

     In actual use, you don't usually call Strncpy or Strncat directly.  The li-
     brary's header file includes two macros which fill in  the  third	argument
     with  sizeof(dst)	for  you.  That way, they can be used as direct replace-
     ments of strcpy and strcat most of the time:

	  char fullName[32];

	  strcpy(fullName, firstName);
	  strcat(fullName, " ");
	  strcat(fullName, lastName);

     This can be transformed into the following, and you can rest  assured  that
     you won't trash the stack if for some reason "firstName" + "lastName" would
     exceed the bounds of "fullName."

	  STRNCPY(fullName, firstName);
	  STRNCAT(fullName, " ");
	  STRNCAT(fullName, lastName);

SEE ALSO
     strcpy(3), strncpy(3), strcat(3), strncat(3), sprintf(3).

West Interactive Corporation						 Strn(3)

Want to link to this manual page? Use this URL:
<https://man.freebsd.org/cgi/man.cgi?query=Strn&sektion=3&manpath=FreeBSD+Ports+15.1.quarterly>

home | help