I have some confusions about what I read from the following site about memcpy()
(and malloc()
):
http://www.cplusplus.com/reference/cstring/memcpy/
In that page,the following 2 lines are clearly stated:
destination
Pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*.
source
Pointer to the source of data to be copied, type-casted to a pointer of type const void*.
But immediately after that,in the code,there is no casting to void*
in the following two lines where memcpy()
is used:
memcpy ( person.name, myname, strlen(myname)+1 );
memcpy ( &person_copy, &person, sizeof(person) );
Please answer the following 2 questions arising from this premise:
1) In C's case(as opposed to C++) is it all right and advisable not to cast to void*
the return type or the arguments in memcpy()
just as it is all right and advisable not to cast to void*
the return type of malloc()
in C?If so,as I intuitively feel, why is it explicitly stated in that reputed site that we need to cast it to void*
(even though it doesn't use that in the code).Is that site wrong about it?
2) Now the real contradiction about that reputed site.Consider the following
http://www.cplusplus.com/reference/cstdlib/malloc/
In the case of malloc()
,in the description, it is written as if it is optional
to cast to void*
the return type (exact words "..can be cast to the desired type
.."),unlike in the case of memcpy()
above where it is said that it is to be cast into void*
.But while in memcpy()
the casting is not done even though it is written that it is to be cast
,in the case of malloc()
,the casting to void*
is done even though it's written it can be cast to void*
.Now I see something wrong in this as for C we are not supposed to cast malloc()
's return to void*
.
To put the discrepancies in a nutshell again lest the people answering get confused in my wordy description:
--Is it advisable in C not to cast to void*
the return and arguments of memcpy()
?
--Is that site wrong about malloc()
as it casts malloc()
return to void*
in C code.
From ISO/IEC 9899:2011 of C language specification, section 6.3.2.3, page 55:
A pointer to
void
may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer tovoid
and back again; the result shall compare equal to the original pointer.
So you basically never need to cast the result of a void*
to the desired type, neither you need to do the opposite.