Chinaunix首页 | 论坛 | 博客
  • 博客访问: 679241
  • 博文数量: 148
  • 博客积分: 4086
  • 博客等级: 上校
  • 技术积分: 1766
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-06 23:27
文章分类

全部博文(148)

文章存档

2013年(19)

2012年(9)

2011年(106)

2009年(14)

分类: WINDOWS

2011-09-17 14:20:01

以下使用strncpy 但不安全
C++代码  收藏代码
  1. #include   
  2. #include   
  3. #include   
  4. #include   
  5.   
  6. int main (int argc, char *argv[])  
  7. {  
  8.     char *p = "hello who you are ? ";  
  9.     char *dest;  
  10.     char s[20];  
  11.     int valLen;  
  12.       
  13.     dest = (char *) malloc (sizeof (char) * 1000);  
  14.   
  15.     //if we use strncpy_s we will get assert  
  16.     //for the size is not enough  
  17.     //we can just change s[20] to s[21]  
  18.     /* 
  19.     strncpy_s(s, _countof(s), p, strlen(p)); 
  20.     printf("%s\n", s); 
  21.     */  
  22.   
  23.   
  24.     // Here we use strncpy and get null termination  
  25.     strncpy (dest, p, (valLen = strlen(p)));  
  26.     dest[valLen] = '\0';  
  27.     printf ("%s\n", dest);  
  28.   
  29.     //system ("pause");  
  30.     return 0;  
  31. }  

以下用strncpy 我们认为它更安全
C++代码  收藏代码
  1. #include   
  2. #include   
  3. #include   
  4. #include   
  5.   
  6. int main (int argc, char *argv[])  
  7. {  
  8.     char *p = "hello who you are ? ";  
  9.     char *dest;  
  10.     char s[20];  
  11.     int valLen;  
  12.       
  13.     dest = (char *) malloc (sizeof (char) * 1000);  
  14.   
  15.     //if we use strncpy_s we will get assert  
  16.     //for the size is not enough  
  17.     //we can just change s[20] to s[21]  
  18.       
  19.     strncpy_s(s, _countof(s), p, strlen(p));  
  20.     printf("%s\n", s);  
  21.       
  22.   
  23.   
  24.     // Here we use strncpy and get null termination  
  25.          /* 
  26.     strncpy (dest, p, (valLen = strlen(p))); 
  27.     dest[valLen] = '\0'; 
  28.     printf ("%s\n", dest); 
  29.          */  
  30.     //system ("pause");  
  31.     return 0;  

阅读(19550) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~