pdest[i] = psrc[i];
}
return dest;
}
char* strcpy(char* to, char* from)
{
char* p = to;
while(*to++ = *from++);
return p;
}
int strcmp(char* a, char* b)
{
while(*a == *b)
++a, ++b;
return *a - *b;
}
char* strcat(char* a, char* b)
{
char* p = a;
while(*a)++a;
while(*a++ = *b++);
return p;
}
int strlen(char* a)
{
int len = 0;
while(*a++)++len;
return len;
}
-----------------------------------------------------------------------------
000
001 # include
002
003 # define BOUNDS_VIOLATED (__builtin_trap (), 0)
004
005 # define CHECK_BOUNDS_LOW(ARG) \
006 (((__ptrvalue (ARG) < __ptrlow (ARG)) && BOUNDS_VIOLATED), \
007 __ptrvalue (ARG))
008
009 # define CHECK_BOUNDS_HIGH(ARG) \
010 (((__ptrvalue (ARG) > __ptrhigh (ARG)) && BOUNDS_VIOLATED), \
011 __ptrvalue (ARG))
012
013 /* copy src to dest */
014 char *
015 strcpy ( char *dest, const char *src)
016 {
017 register char c;
018 char *__unbounded s = (char *__unbounded) CHECK_BOUNDS_LOW (src);
019 const ptrdiff_t off = CHECK_BOUNDS_LOW (dest) - s - 1;
020 size_t n;
021 do {
022 c = *s++;
023 s[off] = c;
024 } while (c != '\0');
025 n = s - src;
026 (void) CHECK_BOUNDS_HIGH (src + n);
027 (void) CHECK_BOUNDS_HIGH (dest + n);
028 return dest;
029 }
030
要注意的有:
1、第003行宏调用的函数为指针越界陷阱系统调用(bounds check,即int $5);
2、第006行的‘&&’和‘,’符号在宏中的用法;
3、数据类型的定义,诸如ptrdiff_t, size_t等的使用;
4、第023的s指针为什么高效,如寄存器使用数量是最少的;
5、第026行为什么要返回void类型
文章出处: