Question

If destination and source are the same, does memmove still "move" the data (or does it return directly)? What about realloc; what if the new size is the same as the old size?

Was it helpful?

Solution

That's really going to be implementation-specific. It would be good practice to do so, sure, but it really depends which implementation you mean.

It's going to work either way, but presumably a suitably clever implementation would check for overlapping segments (and particularly for the case where source == dest) and deal with it appropriately.

OTHER TIPS

As far as I know no standard gives any promises about returning immediately in such case, so you should not expect this behavior.

Better do not pass invalid pointers in hope it's not going to access the data ;-)

At least for realloc, it is implicitly assumed that a "no move necessary" condition exists and is valid, since moving is noted as a special case:

The realloc() function shall change the size of the memory object pointed to by ptr to the size specified by size. The contents of the object shall remain unchanged up to the lesser of the new and old sizes. If the new size of the memory object would require movement of the object, the space for the previous instantiation of the object is freed.

The wording "if... would" suggests that this is not necessarily always so. Of course there is no requirement at all for an implementation to omit a copy that is not necessary.

The only requirement for memmove is that the final effect is the same as if the data was copied to a temporary buffer first and then copied to the final destination. This "as if" constraint allows the copying of overlapping regions without corrupting data (no implementation that I know really copies to a temporary buffer first).

So, in one word: unspecified.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top