S
sam
(newbie)Technically what's the difference between memset() and
memcpy() functions?
memcpy() functions?
sam said:(newbie)Technically what's the difference between memset() and
memcpy() functions?
(newbie)Technically what's the difference between memset() and
memcpy() functions?
(newbie)Technically what's the difference between memset() and
memcpy() functions?
Well, formally, they do different things. Practically, who
cares? You'd never use either in a C++ program.
(newbie)Technically what's the difference between memset() and
memcpy() functions?
Not necessarily. If you are using a library with a C API, and
they require a zeroed POD struct as a param, memset is your
easiest bet.
Yannick said:Read about structure initialisation and remove all these pointless
memset from your code. For example:
http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=171
Yannick said:Strictly speaking, memcpy did not go wrong. It did exactly what was
asked for which is copy byte by byte 20 bytes from address 100 to
address 105.
Is it acceptable to do this:
Foo x = { 0 };
assuming Foo is a POD struct.
That part of my comment was a bit tongue in cheek.
Sorry, this is not undefined behaviour with memcpy().
memcpy()
doesn't care if you try to copy overlapping POD array or C++ objects
overlapping. memcpy() only works with bytes, it is not concerned
about wether these bytes represent an object or a char[] nor if the
destination overlaps with the source, it just does it exactly as
instructed. There result is perfectly defined and predictable. No
undefined behaviour there.
However, if you use memcpy to copy an object partly overlapping over
itself, then you are corrupting memory. Attempting to use this
corrupted memory as a C++ object is undefined behaviour.
Essentially, what you are doing is taking the (void *) which is the
output of the memcpy and casting it to a class type. This is
undefined behaviour if the (void *) did not point to a object of the
class in the first place.
yes it is. This is a *direct quote* from The Standard [1]
"If copying takes place objects that overlap, the behavior is
undefined"
[1] I'm quoting the ANSI *C* standard, because I had it handy.
I'm assuming C++ has not chnaged in this area.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.