What is the difference between
memcpy? Which one do you usually use and how?
From the memcpy man page.
Obviously the source and destination now overlap, we're overwriting
"-bar" with "bar". It's undefined behavior using
The main difference between "memmove()" and "memcpy()" is that in "memmove()", a buffer - a temporary memory - is used; so there is no risk of overlapping. On the other hand, "memcpy()" directly copies the data from the location that is pointed by the source to the location pointed by the destination. (http://www.cplusplus.com/reference/cstring/memcpy/)
Consider the following examples:
As you expected, this will print out:
2) But in this example, the results will not be the same:
It is because "memcpy()" does the following:
I tried running above code : Main reason I want to know the difference of
gives below output
Now I've replaced
simply from the ISO/IEC:9899 standard it is well described.
Which one I usually use acording to the question, depends on what functionallity I need.
In plain text
The technical difference has been documented pretty well by previous answers. The practical differences should be noted as well:
Memcpy will need approximately twice the amount of memory to perform the same task, but memmove could take significantly longer than memcpy.
Say you have a list of 100 items in memory, taking 100 MBs of memory. You want to drop the 1st item so you only have 99.
Memcpy will require the original 100 MBs and an additional 99 MBs for your new list of 99 items. Approximately 199 MBs total to perform the operation, but should be very fast.
Memmove, in the worst scenario will require the original 100 MBs, and will move every item 1 memory address up at a time. This only requires the original 100 MBs, but will be significantly slower than Memcpy.
Of course, creating a new pointer to point at the 2nd item in your list will achieve the same effect of "dropping" the first item from your list, but the example shows the differences in memcpy and memmove well.
-- EDIT TO HELP CLARIFY MY CRAPPY ANSWER --
This creates your list of Items with the first Item missing. This essentially requires no more memory for your program than what it takes to allocate the original ptr_item block of memory. You can't do this using memcpy()...if you did, your program would need to allocate about twice as much memory.
In this second block of code, the program would require twice as much memory as the first block. However, this second block should perform significantly faster than the first block, especially as SIZE increases.
That's how I was trying to explain the practical differences in the two...but perhaps I'm wrong with this as well?