//库函数实现
char *strcat (char *dst, const char *src)
{
char *p = dst;
while (*p)
p++;
while ((*p++ = *src++))
;
return dst;
}
char *strncat (char *s1, const char *s2, long unsigned int n)
{
char *dest = s1;
char c;
while (*s1) s1++;
c = '/0';
while (n > 0)
{
c = *s2++;
*s1++ = c;
if (c == '/0')
return dest;
n--;
}
if (c != '/0')
*s1 = '/0';
return dest;
}
char * strcpy (char *d, const char *s)//
{
char *r = d;
while ((*d++ = *s++));
return r;
}
char *strncpy (char *s1, const char *s2, long unsigned int n)
{
char *dest = s1;
for (; *s2 && n; n--) //n 如果大于s2的长度,则设置0
*s1++ = *s2++;
while (n--)
*s1++ = 0;
return dest;
}
void * memcpy (void *dst, const void *src, long unsigned int n)
{
const char *srcp;
char *dstp;
srcp = src;
dstp = dst;
while (n-- != 0)
*dstp++ = *srcp++;
return dst;
}
void *memmove (void *dst, const void *src, long unsigned int n)
{
const char *srcp;
char *dstp;
srcp = src;
dstp = dst;
if (srcp < dstp)
while (n-- != 0)
dstp[n] = srcp[n];
else
while (n-- != 0)
*dstp++ = *srcp++;
return dst;
}
void *memset (void *dst, int c, long unsigned int n)
{
while (n-- != 0)
n[(char *) dst] = c; // 即 (char*)dst[n] = c;
return dst;
}
库函数力求简洁,因此存在一定的安全的问题,这是在使用过程中特别注意的地方。也因此VC2005才推出_s的所谓的安全函数。也就是多加了判断位。
比如:
char p1[11] = "0123456789";
char *p2 = &p1[5];
strcat(p1, p2);
或
strncat(p1, p2, 5);
会出现很大问题,死循环导致堆栈溢出而core dump