用memmove函数代替strncpy函数
上一篇 /
下一篇 2012-08-29 11:02:12
/ 个人分类:C++
51Testing软件测试网!Z|R3D3kTo+X+h 有过C语言编程的朋友应该都有过指针越界的困扰。不管越界的地方是全局地址、还是局部地址,查起来都是非常麻烦,原因大多时候都来自于自己对
char数组类型的误用。很多同学可能都不是很清楚,在str系类的函数中,函数会在结尾的时候添加NULL指针。比如说strncpy函数,在
linux kernel上是这样写的
?![~'S*F&O0
r5c'X
P0d;d2}kOx0
51Testing软件测试网4Zi QGm#Xx
@]5@+{
51Testing软件测试网:^j)FNw'M /**51Testing软件测试网Vl0w(|r * strncpy - Copy a length-limited, %NUL-terminated string51Testing软件测试网5|V
O'Mvk'@3g * @dest: Where to copy the string to #g S+^(Ru1{U2U0 * @src: Where to copy the string from c:i!Rg&z{0 * @count: The maximum number of bytes to copy &h9F&?I4L2lYr0 * 4czL&{P0 * The result is not %NUL-terminated if the source exceeds51Testing软件测试网b!t.WG)ve * @count bytes. 4d T-R,c"F!u0 */ k"N"}
A?(scG@^0char * strncpy(char * dest,const char *src,size_t count)51Testing软件测试网
t,cn:~:to1h {51Testing软件测试网vP:Xi,{1f q char *tmp = dest;51Testing软件测试网%dta&?zC
51Testing软件测试网0d%gP!eOm while (count) { C:p~P Qvx0 if ((*tmp = *src) != 0) src++;51Testing软件测试网
vTcv k
gj tmp++;51Testing软件测试网@'v$E@2O count--; } A
rKP};dg#v0 } b:\!zR,caDj0 return dest;51Testing软件测试网LE!^ Q
z3{ } :gE6W9x
sq0 |
51Testing软件测试网N#f:QyJO]'RuU 而memmove函数是这样描写的
xmX0B v0
9pV!Y[s
^_RX0
51Testing软件测试网tW)d+V(Hz
nd$Jv9a0/**51Testing软件测试网 I'yXK#ok * memmove - Copy one area of memory to another51Testing软件测试网8i Wc"n3|:CM]hu * @dest: Where to copy to51Testing软件测试网b0g'QhW * @src: Where to copy from51Testing软件测试网7w/L)\5Bf^&x * @count: The size of the area.51Testing软件测试网4O9n;i*[{9i,Yu(I *51Testing软件测试网C sD*Tbfoi'mm~1v\ * Unlike memcpy(), memmove() copes with overlapping areas.51Testing软件测试网{m5c9HOL"pX */51Testing软件测试网G1}1}x*I void * memmove(void * dest,const void *src,size_t count)51Testing软件测试网.f L0?9`T { %ODpYAT*B m)JL0 char *tmp, *s; -^dn'qa\6HRLT0
51Testing软件测试网#\-oYQ)U[ if (dest <= src) { ]|4w;hR2}x0 tmp = (char *) dest;51Testing软件测试网
d,?
q(US`IZ s = (char *) src;51Testing软件测试网7D1|i
D
q while (count--)51Testing软件测试网/Z9B!T!r#ZwKB$pc,o *tmp++ = *s++;51Testing软件测试网E/Yg%`5s!l } 7o~,Z)s cU&X,j!v0 else {51Testing软件测试网1{
n(N9AqS tmp = (char *) dest + count;51Testing软件测试网c%_/T(t"f;R$f s = (char *) src + count; ~*sm4x.yM6l'z0 while (count--)51Testing软件测试网|?&b;M_3_%Z)d7i *--tmp = *--s;51Testing软件测试网"j-dD&w%{ } |