memset (0, 0, 0);

Joern Rennecke
Fri Apr 4 14:54:00 GMT 2003

On some processors, memset can be implemented more efficiently
when you always read - and possibly also write back - the first
memory word contained partially or in whole in the to-be-modified

This conflicts with gdb usage of memset (0, 0, 0); in some places.
There are three practical questions here:
- should gdb use this idiom?
- should all target-specific variants of newlib's memset implement it?
- should all target-specific variants of glibc's memset implement it?

My understanding of the standard is that memset with an unmapped
destination address always invokes undefined behavior.  It says:

   3.14: object:
    ...  Except for bit-fields, objects are composed of contigous
    sequences of one or more bytes, ...
   7.1.7: Use of library functions
    Each of the following statements apply unless explicitly stated
    otherwise in the detailed descriptions that follow.  If an argument
    has an invalid value (such as a value outside the domain of the
    function, or a pointer outside the address space of the program, or
    a null pointer), the behaviour is undefined.  If a function argument
    is described as being an array, the pointer actually passed to the
    function shall have a value such that all address computations and
    accesses to objects (that would be valid if the pointer did point to
    the first element of such an array) are in fact valid. ...
   7.11.1 String function conventions
    The header <string.h> declares one type and several functions, and
    defines one macro useful for manipulating arrays of character type
    and other objects treated as arrays of character type.  ...  in all
    cases a char * or a void * argument points to the initial (lowest
    addressed) character of the array. ... The memset function
    ... void *memset (void *s, int c, size_t n);  ...
    The memset function copies the value of c (converted to unsigned
    char) into each of the first n characters of the object pointed to
    by s.  ...

So, as i understand this, this means that the first argument of memset
must point to an object, which contains at least one (the first)
character.  Passing a NULL pointer, or any other address which is
outside the address space of the program, invokes undefined behaviour.

SuperH (UK) Ltd.
2410 Aztec West / Almondsbury / BRISTOL / BS32 4QX
T:+44 1454 465658

More information about the Newlib mailing list