Chinaunix首页 | 论坛 | 博客
  • 博客访问: 564030
  • 博文数量: 50
  • 博客积分: 571
  • 博客等级: 中士
  • 技术积分: 1162
  • 用 户 组: 普通用户
  • 注册时间: 2012-01-20 14:01
个人简介

希望成为一个有思想,有信仰的程序设计师。

文章分类

全部博文(50)

文章存档

2016年(2)

2015年(2)

2014年(13)

2013年(10)

2012年(23)

分类: C/C++

2014-10-15 22:11:10


点击(此处)折叠或打开

  1. #include <stdio.h>

  2. /***
  3.  * strcmp compare two strings, return less than,equal to , or less than
  4.  *
  5.  * Purpose:
  6.  * strcmp compare two strings and return an integer
  7.  * to indicate whether the first less than the second,
  8.  * the two are squal ,or whether the first is greater than the second
  9.  *
  10.  * Comparison is done byte by byte on an unsigned basis,which is to
  11.  * say that Null(0) is less than any other character(1-255).
  12.  *
  13.  * Entry:
  14.  * const char *src - string for left-hand side of comparison
  15.  * const char *dst - string for right-hand side of comparison
  16.  * Exit:
  17.  * return -1 if src < dst
  18.  * return 0 if src == dst
  19.  * return +1 if src > dst
  20. */

  21. /*
  22. My Vsersion
  23. */
  24. #ifdef __MY_SELF__
  25. int strcmp(const char *src, const char *dst)
  26. {
  27.     int ret = 0;
  28.     while ( !(ret = (unsigned int)*src - (unsigned int)*dst)
  29.             && *src && *dst ) {
  30.         src ++;
  31.         dst ++;
  32.     }
  33.     if (ret > 0) {
  34.         ret = 1;
  35.     } else if (ret < 0) {
  36.         ret = -1;
  37.     }
  38.     return ret;
  39. }
  40. #else
  41. /*
  42. Microsoft Version
  43. */
  44. int __cdecl strcmp (
  45.         const char * src,
  46.         const char * dst
  47.         )
  48. {
  49.         int ret = 0 ;

  50.         while( ! (ret = *(unsigned char *)src - *(unsigned char *)dst) && *dst)
  51.                 ++src, ++dst;

  52.         if ( ret < 0 )
  53.                 ret = -1 ;
  54.         else if ( ret > 0 )
  55.                 ret = 1 ;

  56.         return( ret );
  57. }
  58. #endif // __MY_SELF__
  59. int main()
  60. {
  61.     int ret = 0;
  62.     ret = strcmp("acvb","acv");
  63.     printf("#1 acvb acv res = %d\n");
  64.     ret = strcmp("acvb","acvb");
  65.     printf("#2 acvb acvb res = %d\n");
  66.     ret = strcmp("acb","acv");
  67.     printf("#3 acb acv res = %d\n");
  68.     ret = strcmp("acvgfgffb","acv");
  69.     printf("#4 acvgfgffb acv res = %d\n");
  70.     return 0;
  71. }
上面的代码中有两个版本的strcmp,其中一个是我自己写的,主要目的是为了发现自己思考的漏洞。核心代码就是其他颜色标志出来。可以看出,30行中存在几个问题:
1.类型转换的时候应该使用unsigned char,还有在强制转换指针变量的时候,应该使用53行的方法(unsigned char *),然后在用*运算符取值,这样比较符合规范。
2.条件判断的时候,只要判断*src == 0 或者 *dst == 0就可以了,因为如果长度不同的时候,只要其中一个到达尾部,那么差值必然非0,则循环也就结束了。所以不需要同时判断两个变量是否为0.
3.使用__cdecl关键字,显示的指明函数调用的方式,包括参数传递顺序、堆栈维护职责、名称修饰约定及大小写转换约定。
参考文献:
【1】微软C库的源码
【2】__cdecl MSDN 




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