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 *
10 * The function will copy not more than n bytes (bytes that follow a NUL
11 * character are not copied) from the array pointed to by s1 to the array
12 * pointed to by s2. And it will return s2.
13
14 * method:
15 * -Generate sample string s1 of variable lengths in a loop.
16 * -Use strncpy() to copy s1 into sample string s2 in each iteration
17 * with given n value.
18 * -Truncate last n characters of s1 and
19 * -Compare both strings(s1 and s2) and Also compare returned pointer with s2.
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/1-1.c"
32
random_string(int len)33 char *random_string(int len)
34 {
35 int i;
36 char *output_string = NULL;
37 output_string = malloc(len + 1);
38 if (output_string == NULL) {
39 printf(TNAME " Failed to allocate memory\n");
40 exit(PTS_UNRESOLVED);
41 }
42 for (i = 0; i < len; i++)
43 /* Limiting characters from 1-255 */
44 output_string[i] = rand() % 254 + 1;
45 output_string[len] = '\0';
46 return output_string;
47 }
48
main(void)49 int main(void)
50 {
51 char *ret_str;
52 int i, num_bytes;
53
54 for (i = 1; i < STRING_MAX_LEN; i += STEP_COUNT) {
55 char *sample_str_1;
56 char *sample_str_2 = malloc(i - 1);
57 if (sample_str_2 == NULL) {
58 printf(TNAME " Failed to allocate memory\n");
59 exit(PTS_UNRESOLVED);
60 }
61 sample_str_1 = random_string(i);
62 num_bytes = rand() % i;
63
64 ret_str = strncpy(sample_str_2, sample_str_1, num_bytes);
65
66 sample_str_2[num_bytes] = '\0';
67 sample_str_1[num_bytes] = '\0';
68
69 if (strcmp(sample_str_2, sample_str_1) != 0
70 && ret_str == sample_str_2) {
71 printf(TNAME " Test Failed, string copy failed. "
72 "Expected string: %s\n, But got: %s\n"
73 , sample_str_1, sample_str_2);
74 exit(PTS_FAIL);
75 } else if (ret_str != sample_str_2) {
76 printf(TNAME " Test Failed, return is not as expected. "
77 "Expected: %p, But obtained: %p\n"
78 , sample_str_2, ret_str);
79 exit(PTS_FAIL);
80 }
81 free(sample_str_1);
82 free(sample_str_2);
83 }
84 printf(TNAME " Test Passed, string copied successfully\n");
85 exit(PTS_PASS);
86 }
87