1 /*
2 * This file is licensed under the GPL license. For the full content
3 * of this license, see the COPYING file at the top level of this
4 * source tree.
5 */
6
7 /*
8 * assertion:
9 * If the array pointed to by s1 is a string that is shorter than n bytes,
10 * NUL characters will be appended to the copy in the array pointed to
11 * by s2, until n bytes in all are written
12 *
13 * method:
14 * -Generate sample string s1 of variable lengths in a loop.
15 * -Define number of bytes you want to copy,
16 * which is more than the length of s1.
17 * -Use strncpy to copy string from s1 to s2.
18 * -Check whether s2 is appeneded by '\0' after
19 * writing string s1, till number of bytes given.
20 * -Repeat the above steps for given number of iterations.
21 */
22
23 #include <stdio.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include "posixtest.h"
28
29 #define STRING_MAX_LEN 50000
30 #define STEP_COUNT 2000
31 #define TNAME "strncpy/2-1.c"
32 #define EXTRA_BYTES 10
33
random_string(int len)34 char *random_string(int len)
35 {
36 int i;
37 char *output_string;
38 output_string = malloc(len + 1);
39 if (output_string == NULL) {
40 printf(TNAME " Failed to allocate memory\n");
41 exit(PTS_UNRESOLVED);
42 }
43 for (i = 0; i < len; i++)
44 /* Limiting characters from 1-255 */
45 output_string[i] = rand() % 254 + 1;
46 output_string[len] = '\0';
47 return output_string;
48 }
main(void)49 int main(void)
50 {
51 int i, j, c;
52 char *ret_str;
53
54 for (i = 1; i < STRING_MAX_LEN; i += STEP_COUNT) {
55 c = 0;
56 char *sample_str_1;
57 char *sample_str_2 = malloc(i + EXTRA_BYTES);
58 if (sample_str_2 == NULL) {
59 printf(TNAME " Failed to allocate memory\n");
60 exit(PTS_UNRESOLVED);
61 }
62 sample_str_1 = random_string(i);
63 ret_str = strncpy(sample_str_2, sample_str_1, i + EXTRA_BYTES);
64 sample_str_2[i + EXTRA_BYTES] = '\0';
65
66 if (strcmp(sample_str_1, sample_str_2) != 0) {
67 printf(TNAME " Test failed, string copy failed. "
68 "Expected string: %s, But got: %s\n"
69 , sample_str_1, sample_str_2);
70 exit(PTS_UNRESOLVED);
71 } else if (ret_str != sample_str_2) {
72 printf(TNAME " Test Failed, return is not as expected. "
73 "Expected return: %p, But obtained: %p\n"
74 , sample_str_2, ret_str);
75 exit(PTS_FAIL);
76 }
77
78 for (j = strlen(sample_str_1); j < i + EXTRA_BYTES; j++) {
79 if (sample_str_2[j] == '\0') {
80 c++;
81 }
82 }
83
84 if (c != EXTRA_BYTES) {
85 printf(TNAME " Test Failed, The difference in the number of bytes"
86 " for two strings (s1 and s2) have not been appended"
87 " with NULL bytes\n");
88 exit(PTS_FAIL);
89 }
90 free(sample_str_1);
91 free(sample_str_2);
92 }
93 printf(TNAME " Test Passed, The difference in the number of bytes for two "
94 "strings (s1 and s2) have been appended with NULL bytes in s2\n");
95 exit(PTS_PASS);
96 }
97