// crt_strncpy_x86.c
// compile with: /WX /W3
// processor: x86
#include <stdio.h>
#include <string.h>
int main() {
char a[20] = "test";
char s[20];
char *p = 0, *q = 0;
strcpy_s( s, sizeof(s), "AA BB CC" );
// Note: strncpy is deprecated; consider using strncpy_s instead
strncpy( s, "aa", 2 ); // "aa BB CC" C4996
strncpy( s+3, "bb", 2 ); // "aa bb CC" C4996
strncpy( s, "ZZ", 3 ); // "ZZ", C4996
// count greater than strSource, null added
printf( "%s\n", s );
strcpy_s( s, sizeof(s), "AA BB CC" );
p = strstr(s, "BB");
q = strstr(s, "CC");
strncpy(s, "aa", p - s - 1); // "aa BB CC" C4996
strncpy(p, "bb", q - p - 1); // "aa bb CC" C4996
strncpy(q, "cc", q - s); // "aa bb cc" C4996
strncpy(q, "dd", strlen(q)); // "aa bb dd" C4996
printf( "%s\n", s );
// some problems with strncpy
strcpy_s( s, sizeof(s), "AA BB CC" );
strncpy( s, "this is a very long string", 20 ); // C4996
// Danger: at this point, s has no terminating null
strcpy_s( s, sizeof(s), "dogs like cats" );
strncpy( s+10, "to chase cars", 14); // C4996
// strncpy has caused a buffer overrun and corrupted string a
printf( "Buffer overrun: a = '%s' (should be 'test')\n", a );
// In this case, a is just a char array, but if a were a function
// pointer, this would be an exploitable buffer overrun.
}