关于strcpy, memcpy这几个函数的用途,想必学过C的人都非常了解了。然而在用的时候,怎么样才能用对呢?
当然啦,strcpy有的一个很严重的问题就是可能会出现缓冲区溢出,比如调用函数,在栈上分配的空间,经过strcpy来把返回地址替换导致的缓冲区溢出攻击。所以说最好使用strncpy。但是这里想说的是另外一个问题,内存重叠。首先是一个naive的strcpy实现。
|
|
可以看到,在dest和src不会重叠的情况下,这么做不会出问题。但是万一dest和src重叠,那么就会出现循环无法退出的情况,直至非法访存导致segmentation fault或者导致奇怪的结果。然而查阅文档可以发现,其实strcpy和memcpy这两个函数,都是在内存重叠的情况下未定义的。
strcpyThe behavior is undefined if the strings overlap.
memcpyIf the objects overlap (which is a violation of the restrict contract) (since C99), the behavior is undefined.
所以要安全的使用内存拷贝,应该考虑memmove
he objects may overlap: copying takes place as if the characters were copied to a temporary character array and then the characters were copied from the array to dest.
可以看到,在memmove的glibc-2.25实现中,先会进行判断,如果出现内存重叠,会使用从后往前拷贝的方式。这样就可以解决问题。
|
|