Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!seismo!caip!clyde!burl!ulysses!allegra!alice!ark From: ark@alice.UucP (Andrew Koenig) Newsgroups: net.unix Subject: Re: strdup Message-ID: <6003@alice.uUCp> Date: Sat, 30-Aug-86 12:02:20 EDT Article-I.D.: alice.6003 Posted: Sat Aug 30 12:02:20 1986 Date-Received: Sat, 30-Aug-86 21:45:18 EDT References: <241@bsdpkh.UUCP> Organization: Bell Labs, Murray Hill Lines: 44 > The above code doesn't return a null if malloc fails, so perhaps (for sake > of consistancy) the code should be changed to: > > #define NULL (char *)0 > > char * > strdup(s) > char *s; > { > char *p; > extern char *malloc(); > > if((p = malloc(strlen(s) + 1)) != NULL) > { strcpy(p,s); > return p; > } > return NULL; > } First of all, defining NULL as (char *) 0 is not a good idea. A null pointer is guaranteed to compare equal to a constant 0, so there's no need to cast that 0 to another type. Moreover, if you define NULL the way you have, you generally cannot use it as a null pointer of any other type. Second, malloc takes an unsigned argument, not an int. Third, if malloc returns a null pointer which is then put in p, saying "return p;" will return that null pointer. Thus the program can be shortened: char * strdup(s) char *s; { extern char *malloc(); char *p = malloc ((unsigned) strlen (s) + 1); if (p) strcpy (p, s); return p; } (PS: I have never seen the original code to strdup() either)