473,387 Members | 1,423 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Questions about memmove

Just a few theoretical questions I had on 'memmove':

1. Is there ever a good reason to use memcpy instead of memmove?
2. Is memmove useful to copy structs (as opposed to = operator)?
3. In general, when should memmove explicitly be used? [I have only seen it
used in code to copy char arrays and even then, <string.h> provides most of
the necessary functionality.]
Nov 14 '05 #1
21 5193
Method Man wrote:
Just a few theoretical questions I had on 'memmove':

1. Is there ever a good reason to use memcpy instead of memmove? Yes, when the source and destination do not overlap.
The memcpy function may be more efficient since it doesn't have
to be as careful as memmove.

2. Is memmove useful to copy structs (as opposed to = operator)? As long as the structs do not contain pointers or instances of
structures (which may contain pointers). With pointers, one
runs into ownership and duplication issues.

3. In general, when should memmove explicitly be used? [I have only seen it
used in code to copy char arrays and even then, <string.h> provides most of
the necessary functionality.]

The function memmove should explicity be used when the source and
destination locations overlap.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library

Nov 14 '05 #2

"Method Man" <a@b.c> wrote

1. Is there ever a good reason to use memcpy instead of memmove?
Yes, it makes your intentions clearer if memmove() is reserved for
potentially overlapping regions. Also it may be more efficient to call
memcpy().
2. Is memmove useful to copy structs (as opposed to = operator)?
Use memcpy() for this. Personally I dislike the = operator applied to struct
assignments, since it fails to make clear that this may be an expensive
operation. To people used to other languages, it also fails to make it
obvious that this is a "shallow copy".
3. In general, when should memmove explicitly be used? [I have only seen it used in code to copy char arrays and even then, <string.h> provides most of the necessary functionality.]

Let's say we have an array of objects, and we want to insert an item in the
middle. The items at the end are unused, because the array capacity is
bigger than the actual contents. By calling memove we can move all items up
by one, and then insert our entry.
Since this operation is expensive, it is not used all that often (if you
expect a lot of inserts, you would use a tree or a linked list instead). But
it is still useful on occasions.
Nov 14 '05 #3
Method Man wrote:

Just a few theoretical questions I had on 'memmove':

1. Is there ever a good reason to use memcpy instead of memmove?
If you're copying between nonoverlapping regions of memory.
2. Is memmove useful to copy structs (as opposed to = operator)?
I prefer the assignment operator for stucture copying.
It gives the compiler an oportunity to accomplish the deed
whichever way is best.
If your structure has just a few int type members,
then a structure assignment,
might translate into just a few int assignment instructions.
3. In general, when should memmove explicitly be used?
[I have only seen it used in code to copy char arrays and even then,
<string.h> provides most of the necessary functionality.]


memmove is a string function. What do you mean by
"<string.h> provides most of the necessary functionality."?

--
pete
Nov 14 '05 #4
pete <pf*****@mindspring.com> writes:
Method Man wrote:

[...]
3. In general, when should memmove explicitly be used?
[I have only seen it used in code to copy char arrays and even then,
<string.h> provides most of the necessary functionality.]


memmove is a string function. What do you mean by
"<string.h> provides most of the necessary functionality."?


memmove isn't what I would call a string function, even though it's
declared in <string.h>. It operates on arrays of characters, not on
strings. (A string, by definition, is terminated by a nul character.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #5
Keith Thompson wrote:

pete <pf*****@mindspring.com> writes:
Method Man wrote: [...]
3. In general, when should memmove explicitly be used?
[I have only seen it used in code to copy char arrays and even then,
<string.h> provides most of the necessary functionality.]


memmove is a string function. What do you mean by
"<string.h> provides most of the necessary functionality."?


memmove isn't what I would call a string function,
even though it's declared in <string.h>.


I think that's sufficient to make it a string function.
Both char * and void * arguments are mentioned in the section
of the standard which is labeled "String function conventions".
void * arguments don't apply to any of the string functions
which take pointers to strings as arguments.
It operates on arrays of characters, not on strings.
(A string, by definition, is terminated by a nul character.)


--
pete
Nov 14 '05 #6
> > 2. Is memmove useful to copy structs (as opposed to = operator)?
As long as the structs do not contain pointers or instances of
structures (which may contain pointers). With pointers, one
runs into ownership and duplication issues.


Could you elaborate on this point for me?

Since pointers are just addresses, I don't see why it would be a problem to
copy struct pointers over using 'memmove'. What are the ownership and
duplication issues? I can understand the copying issue with having an
instance of a struct within a struct.

In cases where structs contain a pointer or instance of another struct, what
_would_ happen if memmove was called?
Nov 14 '05 #7
> memmove is a string function. What do you mean by
"<string.h> provides most of the necessary functionality."?


For example, using strcpy or strncpy vs. using memmove to copy char arrays.
Nov 14 '05 #8

"Method Man" <a@b.c> wrote in message

Since pointers are just addresses, I don't see why it would be a problem to copy struct pointers over using 'memmove'. What are the ownership and
duplication issues? I can understand the copying issue with having an
instance of a struct within a struct.


(Untested)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
char *name;
} EMPLOYEE;

EMPLOYEE *employee(const char *name);
void killemployee(EMPLOYEE *emp);
int main(void)
{
EMPLOYEE *emp;
EMPLOYEE *copy;

emp = employee("Fred Bloggs");
copy = employee("Bill Gates");

if(!emp || ! copy)
exit(EXIT_FAILURE);

memmove(copy, emp, sizeof(EMPLOYEE));

killemployee(emp);

printf("Employee left = %s\n", copy->name);

killemployee(copy);

return 0;

}

EMPLOYEE *employee(const char *name)
{
EMPLOYEE *answer;

answer = malloc(sizeof(EMPLOYEE));
if(answer)
{
answer->name = malloc( strlen(name) + 1);
if(!answer->name)
{
free(answer);
return 0;
}
strcpy(answer>name, name));
}

return answer;
}

void killemployee(EMPLOYEE *emp)
{
emp->name[0] = 'X'; /* shred garbage */
free(emp->name);
free(emp);
}
Nov 14 '05 #9
"Malcolm" <ma*****@55bank.freeserve.co.uk> wrote in message news:<cj**********@news6.svr.pol.co.uk>...
"Method Man" <a@b.c> wrote
2. Is memmove useful to copy structs (as opposed to = operator)?

Use memcpy() for this. Personally I dislike the = operator applied to struct
assignments, since it fails to make clear that this may be an expensive
operation. To people used to other languages, it also fails to make it
obvious that this is a "shallow copy".


Yes (though another reason to call attention to structure copy besides
its possible expense, is that it may "alter data in a significant way"
that "=" usually doesn't).

Long long ago, my program failed to read consecutive disk sectors without
"slipping a rev"; there was a lot of cache-checking code, etc. but the
culprit was just an innocuous-looking " sector %= secs_per_trk; "
Obviously I would have noticed and fixed this computational bottleneck
much sooner if the / and % operators were replaced with
"do_a_time_consuming_divide()"

James
Nov 14 '05 #10
"Method Man" <a@b.c> writes:
memmove is a string function. What do you mean by
"<string.h> provides most of the necessary functionality."?


For example, using strcpy or strncpy vs. using memmove to copy char arrays.


If the data you're copying is a counted array of characters, with '\0'
characters considered part of the data, use memmove or memcpy. If
it's a string, terminated by the first '\0' character, use strcpy or
strncpy. The mem* functions and the str* functions work on two
different kinds of data; they're not interchangeable.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #11
Keith Thompson wrote:
"Method Man" <a@b.c> writes:
memmove is a string function. What do you mean by
"<string.h> provides most of the necessary functionality."?
For example, using strcpy or strncpy vs. using memmove to copy char arrays.

If the data you're copying is a counted array of characters, with '\0'
characters considered part of the data, use memmove or memcpy. If
it's a string, terminated by the first '\0' character, use strcpy or
strncpy. The mem* functions and the str* functions work on two
different kinds of data; they're not interchangeable.

No they are not. If you know the length of a string, then memcpy is
usually faster than strcpy and strncpy.

memmove is the only standard function that allows the source and
destination to overlap.


Nov 14 '05 #12
Keith Thompson wrote:
The mem* functions and the str* functions work on two
different kinds of data; they're not interchangeable.


I disagree. The strcmp and strncmp functions,
both interpret the characters as unsigned char,
just like memcmp does.

--
pete
Nov 14 '05 #13
On Sun, 03 Oct 2004 13:12:48 GMT
pete <pf*****@mindspring.com> wrote:
Keith Thompson wrote:
The mem* functions and the str* functions work on two
different kinds of data; they're not interchangeable.


I disagree. The strcmp and strncmp functions,
both interpret the characters as unsigned char,
just like memcmp does.


However, how they interpret a 0 is rather different.

#include <stdio.h>
#include <string.h>

int main (void)
{
char fred[] = { 1,0,2 };
char derf[] = { 1,0,0 };

printf("strcmp gives %d\n",strcmp(fred,derf));
printf("memcmp gives %d\n",memcmp(fred,derf,3));
return 0;
}
--
Flash Gordon
Sometimes I think shooting would be far too good for some people.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #14
>> 2. Is memmove useful to copy structs (as opposed to = operator)?
As long as the structs do not contain pointers or instances of
structures (which may contain pointers). With pointers, one
runs into ownership and duplication issues.


What "ownership and duplication issues" would using memmove() to
copy structs containing pointers have that copying them with =
would NOT have?

Yes, you'll have trouble if you free() the pointer in one of the
structs and then expect the other one to point at valid data.
That happens regardless of the method used to copy.

Gordon L. Burditt
Nov 14 '05 #15

"Malcolm" <ma*****@55bank.freeserve.co.uk> wrote in message
news:cj**********@newsg2.svr.pol.co.uk...

"Method Man" <a@b.c> wrote in message

Since pointers are just addresses, I don't see why it would be a problem

to
copy struct pointers over using 'memmove'. What are the ownership and
duplication issues? I can understand the copying issue with having an
instance of a struct within a struct.


(Untested)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
char *name;
} EMPLOYEE;

EMPLOYEE *employee(const char *name);
void killemployee(EMPLOYEE *emp);
int main(void)
{
EMPLOYEE *emp;
EMPLOYEE *copy;

emp = employee("Fred Bloggs");
copy = employee("Bill Gates");

if(!emp || ! copy)
exit(EXIT_FAILURE);

memmove(copy, emp, sizeof(EMPLOYEE));

killemployee(emp);

printf("Employee left = %s\n", copy->name);

killemployee(copy);

return 0;

}

EMPLOYEE *employee(const char *name)
{
EMPLOYEE *answer;

answer = malloc(sizeof(EMPLOYEE));
if(answer)
{
answer->name = malloc( strlen(name) + 1);
if(!answer->name)
{
free(answer);
return 0;
}
strcpy(answer>name, name));
}

return answer;
}

void killemployee(EMPLOYEE *emp)
{
emp->name[0] = 'X'; /* shred garbage */
free(emp->name);
free(emp);
}


Thanks, I understand the problem.

Now change the line 'memmove(copy, emp, sizeof(EMPLOYEE));' to 'copy =
emp;'. Wouldn't you see the same ownership problem? The difference between
copying structs using memmove vs using =, is what I was orignally interested
in knowing.
Nov 14 '05 #16
In <ln************@nuthaus.mib.org> Keith Thompson <ks***@mib.org> writes:
strncpy. The mem* functions and the str* functions work on two
different kinds of data; they're not interchangeable.


Not entirely true: str* functions can be trivially implemented with mem*
functions. If you know the length of the string to be copied and the
operation is in the program's performance critical path, memcpy (and
setting the null character by hand) is likely to be faster than strcpy,
especially if dealing with long strings.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #17
In <41***********@mindspring.com> pete <pf*****@mindspring.com> writes:
Keith Thompson wrote:
The mem* functions and the str* functions work on two
different kinds of data; they're not interchangeable.


I disagree. The strcmp and strncmp functions,
both interpret the characters as unsigned char,
just like memcmp does.


Yet, they still have different semantics. Compare the behaviour on
the following pair of input string literals: "abcde\0fgh" and "abcde\0fgi"
when n == 9.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #18
On Sun, 3 Oct 2004 19:18:04 -0400
"Method Man" <a@b.c> wrote:

<snip memmove/memcpy vs = for copying structures>
Now change the line 'memmove(copy, emp, sizeof(EMPLOYEE));' to 'copy =
emp;'. Wouldn't you see the same ownership problem? The difference
between copying structs using memmove vs using =, is what I was
orignally interested in knowing.


The differences I can see are that:
1) memmove/memcpy will copy any padding, whereas using = anything could
happen with the padding.
2) the compiler might be able to do clever tricks on the basis that it
knows it is copying a structure.
3) if the compiler doesn't inline memcpy/memmove then these will involve
the overhead of a function call.
4) You could pass a pointere to memcpy/memmove to another function or
store it in a variable, obviously you can't pass a pointer to the =
operator to a function! This is possibly relevant if you are
implementing a scripting language in C.
--
Flash Gordon
Sometimes I think shooting would be far too good for some people.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #19
Flash Gordon <sp**@flash-gordon.me.uk> writes:
On Sun, 3 Oct 2004 19:18:04 -0400
"Method Man" <a@b.c> wrote:

<snip memmove/memcpy vs = for copying structures>
Now change the line 'memmove(copy, emp, sizeof(EMPLOYEE));' to 'copy =
emp;'. Wouldn't you see the same ownership problem? The difference
between copying structs using memmove vs using =, is what I was
orignally interested in knowing.
The differences I can see are that:
1) memmove/memcpy will copy any padding, whereas using = anything could
happen with the padding.


Agreed, and this could be relevant if you later try to compare the
structures using memcmp().
2) the compiler might be able to do clever tricks on the basis that it
knows it is copying a structure.
The compiler is more likely to be able to do clever tricks with an
assignment than with memmove/memcpy, but since they're part of the
standard library the compiler could still do clever tricks even with
the function calls.
3) if the compiler doesn't inline memcpy/memmove then these will involve
the overhead of a function call.


An assignment could also be implemented as a function call.

The smarter the compiler, the less difference there is (at least
potentially) between memcpy() and assignment.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #20

In article <26**************************@posting.google.com >, jd*********@yahoo.com (James Dow Allen) writes:
"Malcolm" <ma*****@55bank.freeserve.co.uk> wrote in message news:<cj**********@news6.svr.pol.co.uk>...
"Method Man" <a@b.c> wrote
2. Is memmove useful to copy structs (as opposed to = operator)?

Use memcpy() for this.
Or, if you'd like another opinion: don't. memcpy has little
advantage over structure assignment except for a dubious one of
documentation (but see below); and it may well have performance
disadvantages in many circumstances.

One possible argument for using memcpy in certain cases is that it
creates a bit-for-bit identical copy, whereas structure assignment is
free to skip padding bytes. Should you later decide to use memcmp to
compare the original structure and its copy, structure assignment
could produce a copy that will compare unequal even though all
members of the two structures are equal. C's lack of a structure
comparison operator aggravates this slightly.

However, I suspect it's rarely very useful to compare two structures
in their entirety, and memcmp seems like a very poor way to do that,
since it's only guaranteed to work in the case where one structure
was copied from the other with memcpy, and neither have been changed
since then. (And perhaps not even then; I haven't looked for cases
where they might still differ.) Comparing each member explicitly
looks much more sensible.
Personally I dislike the = operator applied to struct
assignments, since it fails to make clear that this may be an expensive
operation. To people used to other languages, it also fails to make it
obvious that this is a "shallow copy".

[...]
Long long ago, my program failed to read consecutive disk sectors without
"slipping a rev"; there was a lot of cache-checking code, etc. but the
culprit was just an innocuous-looking " sector %= secs_per_trk; "
Obviously I would have noticed and fixed this computational bottleneck
much sooner if the / and % operators were replaced with
"do_a_time_consuming_divide()"


There's always COBOL, if you want to spell everything out.

C is terse. That's a characteristic of the language. Attempting to
avoid that terseness in a few particular cases, as Malcolm recommends
with memcpy versus structure assignment, strikes me as a fool's
errand. If you're worried that your code may be unclear, add
comments. (And if it's at all likely that someone unfamiliar with C
will be maintaining your code, you have worse problems than their
mistaking the "depth" of C's structure assignment operator.)

--
Michael Wojcik mi************@microfocus.com

An intense imaginative activity accompanied by a psychological and moral
passivity is bound eventually to result in a curbing of the growth to
maturity and in consequent artistic repetitiveness and stultification.
-- D. S. Savage
Nov 14 '05 #21
On Mon, 04 Oct 2004 16:50:04 GMT
Keith Thompson <ks***@mib.org> wrote:
Flash Gordon <sp**@flash-gordon.me.uk> writes:
On Sun, 3 Oct 2004 19:18:04 -0400
"Method Man" <a@b.c> wrote:

<snip memmove/memcpy vs = for copying structures>
Now change the line 'memmove(copy, emp, sizeof(EMPLOYEE));' to

'copy => emp;'. Wouldn't you see the same ownership problem? The
difference> between copying structs using memmove vs using =, is what
I was> orignally interested in knowing.

The differences I can see are that:
1) memmove/memcpy will copy any padding, whereas using = anything
could happen with the padding.


Agreed, and this could be relevant if you later try to compare the
structures using memcmp().


Agreed. However, I wouldn't use memcmp on a structure for the reason we
both know, i.e. you are only guaranteed to get equality if the last
write was the memcpy.
2) the compiler might be able to do clever tricks on the basis that
it knows it is copying a structure.


The compiler is more likely to be able to do clever tricks with an
assignment than with memmove/memcpy, but since they're part of the
standard library the compiler could still do clever tricks even with
the function calls.


Indeed. In fact, due to the difficulty of doing clever things with
structures and the simplicity of inlining and potentially optimising
memcpy calls I would not be surprised if the compiler implemented the
assignment as a memcpy.
3) if the compiler doesn't inline memcpy/memmove then these will
involve the overhead of a function call.


An assignment could also be implemented as a function call.

The smarter the compiler, the less difference there is (at least
potentially) between memcpy() and assignment.


Agreed. I would generally use assignment because it is less typing.
--
Flash Gordon
Sometimes I think shooting would be far too good for some people.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #22

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: rinku24 | last post by:
What is the difference between memcpy and memmove? Which is more expensive?
71
by: ROSY | last post by:
1. How would you use the functions memcpy(), memset(), memmove()?
21
by: Mac | last post by:
$ cat junk27.c #include <stdio.h> #include <string.h> int main (void) { printf("The difference between memcpy and memmove is %ld\n", (long int) memcpy - (long int) memmove); return 0; }
12
by: Ian | last post by:
I read the FAQ about the differences between memcpy() and memmove(). Apparently memmove() is supposed to be safer. Just to make sure I understand the concept of memmove(), can someone tell me if...
6
by: novice | last post by:
Please explain with an example whts the DIFFERENCE between "memcpy" and "memmove"
1
by: kyo guan | last post by:
Hi : python list object like a stl vector, if insert a object in the front or the middle of it, all the object after the insert point need to move backward. look at this code ( in python...
5
by: xdevel | last post by:
Hi, anyone can make me an example where memmove does not cause a memory overlapping and where memcpy do it? Thanks
14
by: somenath | last post by:
Hi All, I am trying to understand the behavior of the memcpy and memmove. While doing so I wrote a program as mentioned bellow . #include<stdio.h> #include<stdlib.h> #include<string.h> ...
3
by: Chris | last post by:
Hello all, Not sure if this is off topic, if it is I apologise in advance. Is it safe to use memmove() on an array of objects? I create an array of Objects and I have a cursor to indicate...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.