futrueboy 发表于 2013-1-27 04:59:57

使用strncpy_s 比 使用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;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 to s/*strncpy_s(s, _countof(s), p, strlen(p));printf("%s\n", s);*/    // Here we use strncpy and get null terminationstrncpy (dest, p, (valLen = strlen(p)));dest = '\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;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 to s   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 = '\0';printf ("%s\n", dest);         *///system ("pause");return 0;}
页: [1]
查看完整版本: 使用strncpy_s 比 使用strncpy更加安全