Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is overlapping in memmove() definition?

Tags:

c++

c

overlapping

I was reading from a c++ reference about memcpyand memmove and they seems to be doing the same thing except that memmove has a specific think called (allowing the destination and source to overlap).

What is overlapping and when that happens?

like image 909
rullof Avatar asked Dec 22 '13 02:12

rullof


People also ask

What is overlapping memory?

In human memory research, concurrent overlap, or task appropriate processing, is a type of processing overlap between an activity engaged in before the prospective memory is to be remembered and a cue that directs attention towards the prospective memory.

What does overlap mean in C?

If the memory segments coincide at some point, a "overlapping" would occur. Imagine a memory segment starts at address 0x51, and the other starts at address 0x70, and you try to copy 50 bytes from 0x51 to 0x70... at some point, the process will start reading from address at 0x70, and copying to address 0x8F.

Can memcpy overlap?

The CRT function memcpy doesn't support overlapping memory. The CRT provides an alternative to memcpy that does support overlapping memory: memmove .

What is Memmove function in C?

memmove() is used to copy a block of memory from a location to another. It is declared in string.h. // Copies "numBytes" bytes from address "from" to address "to" void * memmove(void *to, const void *from, size_t numBytes);


1 Answers

It's very simple. Consider memmove(dest, source, length).

If the range of bytes specified by the range source to source + length - 1 include any bytes in the range specified by dest to dest + length - 1, the two ranges overlap.

This is most likely to happen when moving elements within an array. Example:

// Slide array down by one:
char array[N];
memmove( (void*) &array[0], (void*) &array[1], N - 1 );

That overlaps on elements 1 through N-2. Sliding the other direction has a similar overlap:

// Slide array up by one:
memmove( (void*) &array[1], (void*) &array[0], N - 1 );

If you were to attempt this same operation with memcpy(), the resulting behavior is undefined. Some implementations will work correctly if you use memcpy in both examples above. Others will fail for one or both of the two if you use memcpy here instead of memmove. This is a consequence of the fact C and C++ leave the behavior undefined for memcpy() when the ranges overlap like this.

like image 197
Joe Z Avatar answered Oct 03 '22 01:10

Joe Z