1 #include <string.h> 2 #include <stdio.h> 3 4 char b[50]; 5 6 void reset_b(void) 7 { 8 int i; 9 10 for (i = 0; i < 50; i++) 11 b[i] = '_'; 12 b[49] = '\0'; 13 } 14 15 void reset_b2(void) 16 { 17 reset_b(); 18 strcpy(b, "ABCDEFG"); 19 } 20 21 int main(void) 22 { 23 char x[100]; 24 char a[] = "abcdefghijklmnopqrstuvwxyz"; 25 int i; 26 27 /* testing memcpy/strcpy overlap */ 28 29 for (i = 0; i < 50; i++) { 30 x[i] = i+1; // don't put any zeroes in there 31 } 32 for (i = 50; i < 100; i++) { 33 // because of the errors, the strcpy's will overrun, so put some 34 // zeroes in the second half to stop them eventually 35 x[i] = 0; 36 37 } 38 39 memcpy(x+20, x, 20); // ok 40 memcpy(x+20, x, 21); // overlap 41 memcpy(x, x+20, 20); // ok 42 memcpy(x, x+20, 21); // overlap 43 44 strncpy(x+20, x, 20); // ok 45 strncpy(x+20, x, 21); // overlap 46 strncpy(x, x+20, 20); // ok 47 strncpy(x, x+20, 21); // overlap 48 49 x[39] = '\0'; 50 strcpy(x, x+20); // ok 51 52 x[39] = 39; 53 x[40] = '\0'; 54 strcpy(x, x+20); // overlap 55 56 x[19] = '\0'; 57 strcpy(x+20, x); // ok 58 59 /* 60 x[19] = 19; 61 x[20] = '\0'; 62 strcpy(x+20, x); // overlap, but runs forever (or until it seg faults) 63 */ 64 65 /* testing strcpy, strncpy() */ 66 67 reset_b(); 68 printf("`%s'\n", b); 69 70 strcpy(b, a); 71 printf("`%s'\n", b); 72 73 reset_b(); 74 strncpy(b, a, 25); 75 printf("`%s'\n", b); 76 77 reset_b(); 78 strncpy(b, a, 26); 79 printf("`%s'\n", b); 80 81 reset_b(); 82 strncpy(b, a, 27); 83 printf("`%s'\n", b); 84 85 printf("\n"); 86 87 /* testing strncat() */ 88 89 reset_b2(); 90 printf("`%s'\n", b); 91 92 reset_b2(); 93 strcat(b, a); 94 printf("`%s'\n", b); 95 96 reset_b2(); 97 strncat(b, a, 25); 98 printf("`%s'\n", b); 99 100 reset_b2(); 101 strncat(b, a, 26); 102 printf("`%s'\n", b); 103 104 reset_b2(); 105 strncat(b, a, 27); 106 printf("`%s'\n", b); 107 108 /* Nb: can't actually get strcat warning -- if any overlap occurs, it will 109 always run forever, I think... */ 110 111 for ( i = 0; i < 2; i++) 112 strncat(a+20, a, 21); // run twice to check 2nd error isn't shown 113 strncat(a, a+20, 21); 114 115 /* This is ok, but once gave a warning when strncpy() was wrong, 116 and used 'n' for the length, even when the src was shorter than 'n' */ 117 { 118 char dest[64]; 119 char src [16]; 120 strcpy( src, "short" ); 121 strncpy( dest, src, 20 ); 122 } 123 124 return 0; 125 } 126