memcpy(0,0,0)

R

remove the CAPS

Hi, all.

This question came up in a code review: are null pointers legal as
arguments to memcpy? That is, is the program at the end of this article
strictly conforming? (Of course, I check the FAQ first and could not
find an answer on point.)

I don't have C89 or C99 handy, so I checked draft N869 from here:
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n869/n869.txt.gz

I note the following:

7.21.1 String function conventions
Where an argument declared as "size_t n" specifies the
length of the array for a function, "n" can have the value
zero on a call to that function. Unless explicitly stated
otherwise in the description of a particular function in
this subclause, pointer arguments on such a call shall still
have valid values, as described in 7.1.4.

7.21.2.1 The memcpy function
void *memcpy(void * restrict s1,
const void * restrict s2,
size_t n);
[But see N869 for complete text].

7.1.4 Use of library functions
... unless explicitly stated otherwise in the
detailed descriptions ...
If an argument to a function has an invalid
value (such as ... a null pointer) ... the behavior
is undefined.

So, by my analysis, 7.1.4 says that you must not pass a null pointer to
any library function unless the 7.X documentation allows it. 7.21.1
reenforces 7.1.4, and does not explicity allow a null pointer. 7.21.2.1
also does not explicitly allow a null pointer.

So, memcpy(0,0,0) invokes undefined behavior?

Regards,

Rob

#include <string.h>
int main(void)
{
memcpy(0,0,0);
return 0;
}
 
C

Christopher Benson-Manica

remove the CAPS said:
This question came up in a code review: are null pointers legal as
arguments to memcpy? That is, is the program at the end of this article
strictly conforming? (Of course, I check the FAQ first and could not
find an answer on point.)
So, memcpy(0,0,0) invokes undefined behavior?

Yes.

http://snipurl.com/i0ej

(Note that I asked essentially the same question, two years ago, so
you are not alone in wondering.)
 

Ask a Question

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.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,223
Latest member
Jurgen2087

Latest Threads

Top