用memmove函数代替strncpy函数

上一篇 / 下一篇  2012-08-29 11:02:12 / 个人分类:C++

}U[b9I5a|z0  有过C语言编程的朋友应该都有过指针越界的困扰。不管越界的地方是全局地址、还是局部地址,查起来都是非常麻烦,原因大多时候都来自于自己对 char数组类型的误用。很多同学可能都不是很清楚,在str系类的函数中,函数会在结尾的时候添加NULL指针。比如说strncpy函数,在 linux kernel上是这样写的51Testing软件测试网/i#M)c5{#mN\5X6t

F u"\^7Q5n0 51Testing软件测试网r Aa,KA\.D2h

51Testing软件测试网x6Kzr)AC9x Yw

/**
$Pxfw3S:f |x hi%o0 * strncpy - Copy a length-limited, %NUL-terminated string
_!] j0I%b$Ce0 * @dest: Where to copy the string to51Testing软件测试网#ih7yN!~~es
 * @src: Where to copy the string from
hXsLv5kR,UQ#M6w0 * @count: The maximum number of bytes to copy
,]+[^ qn`^0 *51Testing软件测试网@1B6C;A Q.x-U
 * The result is not %NUL-terminated if the source exceeds51Testing软件测试网h"] eyN!T1zVH8d
 * @count bytes.51Testing软件测试网S(|VZ;I(bk#B#V
 */
QKkH}h @l3_c'k0char * strncpy(char * dest,const char *src,size_t count)51Testing软件测试网zQW|3h
{
D WJ4x*W#v/e?0 char *tmp = dest;

(@`-|HW]f/f0

,X#Z5j5H8FsAfU0 while (count) {51Testing软件测试网8v:T8B3cl2@ Z V3yL_-v
  if ((*tmp = *src) != 0) src++;
r3AQ@ x0s2b mQM/W0  tmp++;
1vqT'|EC*jN+g0  count--;51Testing软件测试网9w,Fy\C4A D+U FQ
 }
7W-c*xJ CC0 return dest;
0@(O pzS|8M0}

h EgB y&z0

RJK!c%S0  而memmove函数是这样描写的

OD n-s*MK0

R1~(MG f3c'd'N0 51Testing软件测试网 ^qQKJGR

Khs5QdB[0/**
TZ^1`lq-u0 * memmove - Copy one area of memory to another51Testing软件测试网J,MI2E!i3J{)E
 * @dest: Where to copy to
Y%`~6c(u:Y2h)J&w0 * @src: Where to copy from51Testing软件测试网&v%w&}9I#?&w N/zv/`
 * @count: The size of the area.51Testing软件测试网3eiA+m,I!?{J
 *51Testing软件测试网_Y#gng/Fa
 * Unlike memcpy(), memmove() copes with overlapping areas.51Testing软件测试网I&C:aD.Ax
 */
/J!V#h(vr]p0void * memmove(void * dest,const void *src,size_t count)
K.?$v D&kL e0{
'?E T2?{E$`(X7r0 char *tmp, *s;
51Testing软件测试网 U s lk3gv { C9W(u

.\O%D2Rj,G"E7~ U0 if (dest <= src) {51Testing软件测试网S;bo @CB)]A Y%`,\
  tmp = (char *) dest;
NNR7M5Wi8sZ0  s = (char *) src;
c*n"YL1b$l0  while (count--)
rfP9Hl X#T0   *tmp++ = *s++;51Testing软件测试网f'k&R)\fP B/j7WvJr
  }
WZ3ZWL u0[YU8C0 else {51Testing软件测试网w B?-q8NFJg
  tmp = (char *) dest + count;
a#~)U#E-@ T\0  s = (char *) src + count;51Testing软件测试网 u~T;H?nQ3r
  while (count--)51Testing软件测试网v JMr:cvH(s
   *--tmp = *--s;51Testing软件测试网%K3CJwr gY8]
  }
51Testing软件测试网~i hR{

vW^6C{&aA0 return dest;51Testing软件测试网bL"{m8W x8gL
}

E.q(EZ/Iz$@ W'T0
51Testing软件测试网#@}c!KgwOG

  通过上面的代码,我们发现memmove函数有几个好处:

#k.Q'y6tb&d@0 51Testing软件测试网n_u]Y-E2m5| w'j

  (1)会根据dest和src的地址关系灵活判断复制顺序;51Testing软件测试网x!`M I8rs f-f'e Df

X&xFF$Er0  (2)不会额外添加NULL指针;51Testing软件测试网(O"eu!Bc}

51Testing软件测试网:c0Z8Y+qcm ^2l;h

  (3)需要自己时刻关心当前字符串的大小问题;

pD:g L\0

3oKK2V@#B0  (4)memmove可以应用于各种数据结构,而不仅仅是char*类型。

zB`#U9O?0

TAG:

 

评分:0

我来说两句

Open Toolbar