1 #include <stdio.h>
2 #include <stdlib.h>
3 
4 #define _GNU_SOURCE
5 #include <string.h>
6 
7 int main(int argc, char **argv)
8 {
9   char a[] = "The spazzy orange tiger jumped over the tawny jaguar.";
10   char *b, *c;
11   char *d, *e;
12 
13   size_t l = strlen (a);
14   fprintf (stderr, "strlen: %zd\n", l); // strlen: 53
15 
16   b = (char *) malloc((l + 3)); // Extra space for some zeros.
17   b[l] = 'X';
18   b[l + 1] = 'X';
19   b[l + 2] = 'X';
20   c = stpncpy (b, a, l + 3);
21 
22   fprintf (stderr, "equal: %d\n", strcmp (a, b)); // equal: 0
23   fprintf (stderr, "retlen: %zd\n", c - b); // retlen: 53
24   fprintf (stderr, "last: '%c'\n", *(c - 1)); // last: '.'
25   fprintf (stderr, "zero0: %d\n", *c); // zero0: 0
26   fprintf (stderr, "zero1: %d\n", *(c + 1)); // zero1: 0
27   fprintf (stderr, "zero2: %d\n", *(c + 2)); // zero2: 0
28 
29   d = (char *) malloc (l - 1); // No room for zero termination or dot.
30   e = stpncpy (d, b, l - 1);
31 
32   fprintf (stderr, "equal: %d\n", strncmp (b, d, l - 1)); // equal: 0
33   fprintf (stderr, "retlen: %zd\n", e - d); // retlen: 52
34   fprintf (stderr, "last: '%c'\n", *(e - 1)); // last: 'r'
35 
36   free (b);
37   free (d);
38   return 0;
39 }
40