strdup

Andrew Koenig ark at alice.UucP
Sun Aug 31 02:02:20 AEST 1986


> 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)



More information about the Comp.unix mailing list