Strcpy on SysV vs. BSD.

Chris Torek chris at mimsy.umd.edu
Sun Sep 2 08:02:40 AEST 1990


>In article <24351 at adm.BRL.MIL> hsw at sparta.com (Howard Weiss) writes:
[Judging from your address, you probably sent this to a mailing list.
 Nonetheless, this is the wrong place for it.  The proper place is
 comp.lang.c, aka INFO-C, although I do not recall the list redistribution
 site.]
>>main(){
>>  char *TTx = "/dev/", *tty;
>>  strcpy(tty,TTx);
>>}

In article <1990Aug31.202707.14353 at dg-rtp.dg.com>
hunt at dg-rtp.dg.com (Greg Hunt) writes:
>The problem isn't with strcpy, SysV, or BSD, there is an error in the
>program.

Correct.

>This didn't occur, as you noted, when you used 'char tty [10];',
>because tty in that case is a pointer to an array of characters and ....

Not quite.  When declared as an array, `tty' *IS* an array.  (The
only exception to this occurs when declaring formal parameters.)  This
means that sizeof(tty) is 10*sizeof(char), and `&tty' is a value
of type `pointer to array 10 of char' (or, in Classic C, simply an
error).  In other contexts, `tty' *ACTS LIKE* a pointer.  That does
not make it one.

Whenever an array object is used in a value (aka `rvalue') context, the
compiler changes the triple <object, array N of T, foo> to the triple
<value, pointer to T, &foo[0]>.  Here, if you change the program to

	main() {
		char *strcpy();
		char tty[10];
		strcpy(tty, "/dev/");
	}

the call to strcpy is originally:

	[CALL] <object, function returning pointer to char, strcpy>
	  [ARGUMENT] <object, array 10 of char, tty>
	  [ARGUMENT] <object, array 6 of char, "/dev/">

The two arguments are both in value contexts, so they both undergo the
usual conversion, and the compiler comes up with

	[CALL] <object, function returning pointer to char, strcpy>
	  [ARGUMENT] <value, pointer to char, &tty[0]>
	  [ARGUMENT] <value, pointer to char, '/' in { / d e v / \000 }>

In the CALL context the function object also converts (to a pointer to
the corresponding function); and the compiler then arranges for the
converted arguments to be stuffed into an envelope, sealed, stamped,
and mailed off to strcpy() ... or whatever else is a convenient way to
get them there.

(In New C, strcpy as declared above is `function (unknown args)
returning pointer to char', rather than `function returning pointer to
char'; using `#include <string.h>' would get `pointer to function
(pointer to char, pointer to readonly char) returning pointer to
char'.  This allows the compiler to type-check the arguments.)
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 405 2750)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.unix.questions mailing list