memmove

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
PlayOS

memmove

Post by PlayOS »

Hi all,

I just have a question about memmove(). The prototype for this finction is

void * memmove ( void * dest, const void * src, size_t num );

Really this function is only good for working on a buffer that is both the dest and src because it is impossible for two different variables to have overlapping addresses, unless one is a reference to another, which would be the same as the dest and src being that same.

So from the prototype you would expect that src would not be modified because it is going in as const, but what if the following situation happens?

Let's say that we do this

char* pDst = "This is a string!...";

memmove(pDst+8, pDst+5, 12);

This would produce the following string

"This is is a string!"

However now src has been modified, not by it's reference but none the less it is still modified!

Becasue src is pDst+5 and goes for 12 bytes from byte 3 of the copy, the src is changed.

So can someone tell me why the prototype is const void* src, isn't this incorrect?
Schol-R-LEA

Re:memmove

Post by Schol-R-LEA »

Actually, overlapping memory areas do come up in actual practice, especially in the case of text editing.

Most editors use one large buffer to hold all of a file (or at least as much as will load into memory), and a smaller buffer in which the editing actually takes place. At any given time, the main buffer is split into two sections: the area from the beginning of the file to the beginning of the focus buffer, which is mapped into the beginning of the buffer, and area after the focus buffer, which is often pushed to the end of the buffer. Whenever the focus buffer is more than half-filled, or when the focus is moved, the focus buffer's contents are appended to the top half and then loaded with whatever is the next are to be modified (or, if the editor is insert mode, it is simply cleared). If the focus in a very large file is move from one end to the other (from near the top to near the bottom, or vis versa), it is possible that some of the moved text would overlap itself.
Post Reply