以下使用strncpy 但不安全
以下用strncpy 我们认为它更安全
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <windows.h>
int main (int argc, char *argv[])
{
char *p = "hello who you are ? ";
char *dest;
char s[20];
int valLen;
dest = (char *) malloc (sizeof (char) * 1000);
//if we use strncpy_s we will get assert
//for the size is not enough
//we can just change s[20] to s[21]
/*
strncpy_s(s, _countof(s), p, strlen(p));
printf("%s\n", s);
*/
// Here we use strncpy and get null termination
strncpy (dest, p, (valLen = strlen(p)));
dest[valLen] = '\0';
printf ("%s\n", dest);
//system ("pause");
return 0;
}
以下用strncpy 我们认为它更安全
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <windows.h>
int main (int argc, char *argv[])
{
char *p = "hello who you are ? ";
char *dest;
char s[20];
int valLen;
dest = (char *) malloc (sizeof (char) * 1000);
//if we use strncpy_s we will get assert
//for the size is not enough
//we can just change s[20] to s[21]
strncpy_s(s, _countof(s), p, strlen(p));
printf("%s\n", s);
// Here we use strncpy and get null termination
/*
strncpy (dest, p, (valLen = strlen(p)));
dest[valLen] = '\0';
printf ("%s\n", dest);
*/
//system ("pause");
return 0;
}