strdup

Paul K Heffner heff at bsdpkh.UUCP
Sat Aug 30 02:50:32 AEST 1986


hjb writes:

> /* the following code is in the public domain.  I have never seen */
> /* the original UNIX code for this function. */
> /* hjb 08/25/86 */
> 
> char *
> strdup(s)
> char *s;
> {
> 	char *p;
> 	extern char *malloc();
> 
> 	if(p=malloc(strlen(s)+1))
> 		strcpy(p,s);
> 	return p;
> }
> 
> I am not sure, but I think that strdup comes from MicroSoft, and is only
> present under XENIX and their MSDOS C compiler.  It's a useful function,
> though, and everybody should have it.

I'm using the latest release of the Software Generation System on an AT&T
3b2 and strdup is indeed found in STRING(3C). Following is the description
from the man page:

char *strdup (s1)
char *s1;

Strdup returns a pointer to a new string which is a duplicate of the string
pointed to by s1. The space for the new string is obtained using malloc(3C). If
the new string cannot be created, null is returned.

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;
}

						Paul Heffner
					{ihnp4,akgua,attmail}!bsdpkh!heff



More information about the Comp.unix mailing list