[comp.std.c] Interpretation question: Pointers to explicitly zero-length strings

leichter@CS.YALE.EDU (Jerry Leichter) (07/08/89)

A number of the ANSI C library functions accept a string argument, together
with a maximum length.  Obvious examples include strncpy and printf (%s can
accept a maximum length).  If the maximum length given is zero, must the
pointer passed be valid?  In particular, may it be 0, as in:

	strncpy(s,NULL,0);

This may sound like a silly question if you look only at an isolated example
with constants in it, but it arises naturally when dealing with strings
represented using a (length,pointer) structure.  When the length is 0, it
makes little difference where the pointer points, but it is often simplest -
in initialization, for example - to let it just be 0.

							-- Jerry

dfp@cbnewsl.ATT.COM (david.f.prosser) (07/10/89)

In article <65745@yale-celray.yale.UUCP> leichter@CS.YALE.EDU (Jerry Leichter) writes:
>A number of the ANSI C library functions accept a string argument, together
>with a maximum length.  Obvious examples include strncpy and printf (%s can
>accept a maximum length).  If the maximum length given is zero, must the
>pointer passed be valid?  In particular, may it be 0, as in:
>
>	strncpy(s,NULL,0);
>
>This may sound like a silly question if you look only at an isolated example
>with constants in it, but it arises naturally when dealing with strings
>represented using a (length,pointer) structure.  When the length is 0, it
>makes little difference where the pointer points, but it is often simplest -
>in initialization, for example - to let it just be 0.
>
>							-- Jerry

The question is certainly not silly.  Unfortunately, the answer is that
there is no guarantee of reasonable behavior in general in these situations.

Only if the pANS has an explicit description that allows for an invalid
pointer value when the length is zero (such as is present for strxfrm)
is passing NULL (or other invalid pointer value) strictly conforming.

The reason is that some functions, when mapped to some architectures' zippy
instructions, may still require valid addresses even if no bytes of any
object need be accessed.  This is particularly the case for functions like
memcpy.

Dave Prosser	...not an official X3J11 answer...

gwyn@smoke.BRL.MIL (Doug Gwyn) (07/11/89)

In article <65745@yale-celray.yale.UUCP> leichter@CS.YALE.EDU (Jerry Leichter) writes:
>If the maximum length given is zero, must the pointer passed be valid?

Yes, unless the case of a null pointer is explicitly given special
semantics, any pointer described as pointing to a string must in
fact point to a valid string.  The implementation is entitled to
access the first byte pointed to, even if it might not be logically
necessary in order to determine the result in the 0-length case.

Disclaimer: Not an official X3J11 statement.