问题描述
我想了解和,我已阅读文字的memcpy()
不照顾重叠的源和目标,而 memmove与()
一样。
然而,当我上重叠的存储器块执行这两个功能,它们都得到相同的结果。例如,拿 memmove与()
帮助页面上的以下MSDN例如: -
有没有更好的例子来理解的memcpy
的弊端,以及如何 memmove与
解决它?
// crt_memcpy.c
//举例说明重叠的副本:memmove与始终正确处理它;的memcpy可以处理
正确//它。#包括LT&;&memory.h GT;
#包括LT&;&string.h中GT;
#包括LT&;&stdio.h中GT;炭STR1 [7] =为aabbcc;INT主要(无效)
{
的printf(字符串:%S \\ n,STR1);
的memcpy(STR1 + 2,STR1,4);
的printf(新的字符串:%S \\ n,STR1); strcpy_s(STR1,sizeof的(STR1),为aabbcc); //复位字符串 的printf(字符串:%S \\ n,STR1);
的memmove(STR1 + 2,STR1,4);
的printf(新的字符串:%S \\ n,STR1);
}
输出:
的字符串:为aabbcc
新的字符串:aaaabb
字符串:为aabbcc
新的字符串:aaaabb
我并不完全感到惊讶,你的榜样,没有表现出奇怪的行为。请尝试复制 STR1
到 STR1 + 2
,而不是看然后会发生什么。 (实际上可能没有有所作为,取决于编译器/库)。
在一般情况下,memcpy的在一个简单的(但快速的方式)被实现。简单地说,它只是循环通过数据(按顺序),复制从一个位置到另一个。这可导致在源,而它的被读出被覆盖。
memmove与做更多的工作,以确保正确处理重叠。
编辑:
(不幸的是,我无法找到像样的例子,但这些都行)。对比和这里显示的实现。的memcpy只是循环,同时的memmove执行一个测试,以确定,以避免破坏数据哪个方向环路英寸这些实现是相当简单的。最高性能实现更复杂的(包括在一个时间,而不是字节复制字大小的块)。
I am trying to understand the difference between memcpy()
and memmove()
, and I have read the text that memcpy()
doesn't take care of the overlapping source and destination whereas memmove()
does.
However, when I execute these two functions on overlapping memory blocks, they both give the same result. For instance, take the following MSDN example on the memmove()
help page:-
Is there a better example to understand the drawbacks of memcpy
and how memmove
solves it?
// crt_memcpy.c
// Illustrate overlapping copy: memmove always handles it correctly; memcpy may handle
// it correctly.
#include <memory.h>
#include <string.h>
#include <stdio.h>
char str1[7] = "aabbcc";
int main( void )
{
printf( "The string: %s\n", str1 );
memcpy( str1 + 2, str1, 4 );
printf( "New string: %s\n", str1 );
strcpy_s( str1, sizeof(str1), "aabbcc" ); // reset string
printf( "The string: %s\n", str1 );
memmove( str1 + 2, str1, 4 );
printf( "New string: %s\n", str1 );
}
Output:
The string: aabbcc
New string: aaaabb
The string: aabbcc
New string: aaaabb
I'm not entirely surprised that your example exhibits no strange behaviour. Try copying str1
to str1+2
instead and see what happens then. (May not actually make a difference, depends on compiler/libraries).
In general, memcpy is implemented in a simple (but fast manner). Simplistically, it just loops over the data (in order), copying from one location to the other. This can result in the source being overwritten while it's being read.
Memmove does more work to ensure it handles the overlap correctly.
EDIT:
(unfortunately, I can't find decent examples, but these will do). Contrast the memcpy and memmove implementations shown here. memcpy just loops, while memmove performs a test to determine which direction to loop in to avoid corrupting the data. These implementations are rather simple. Most high-performance implementations are more complicated (involving copying word-size blocks at a time rather than bytes).
这篇关于的memcpy()的memmove VS()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!