六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 56|回复: 0

使用strncpy_s 比 使用strncpy更加安全

[复制链接]

升级  3.33%

13

主题

13

主题

13

主题

秀才

Rank: 2

积分
55
 楼主| 发表于 2013-1-27 04:59:57 | 显示全部楼层 |阅读模式
以下使用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 terminationstrncpy (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;}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表