用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
|xhi%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@ ZV3yL_-v if ((*tmp = *src) != 0) src++; r3AQ@
x0s2bmQM/W0 tmp++; 1vqT'|EC*j N+g0 count--;51Testing软件测试网9w,Fy\C4A
D+U FQ } 7W-c*xJ C C0 return dest; 0@(O
pzS|8M0} h EgB
y&z0 |
RJK!c%S0 而memmove函数是这样描写的
OD n-s*MK0
R1~(MGf3c'd'N0
51Testing软件测试网
^qQKJGR
Khs5Qd B[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#?&wN/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; NNR7M5W i8sZ0 s = (char *) src;
|