*BSD News Article 5898


Return to BSD News archive

Xref: sserve comp.unix.bsd:5946 comp.sys.ibm.pc.rt:1686 comp.unix.large:617
Newsgroups: comp.unix.bsd,comp.sys.ibm.pc.rt,comp.unix.large
Path: sserve!manuel!munnari.oz.au!metro!mama!andy
From: andy@research.canon.oz.au (Andy Newman)
Subject: Re: strdup
Message-ID: <BvH0FK.K1I@research.canon.oz.au>
Sender: news@research.canon.oz.au
Organization: Canon Information Systems Research Australia
References: <br.pct.52.717898310@RLG.Stanford.EDU> <lckirmINNosg@spim.mti.sgi.com>
Date: Fri, 2 Oct 1992 01:35:44 GMT
Lines: 20

koblas@mips.com (David Koblas) writes:
>
>Here's a copy (typed in off the cuff, so I won't say it is guaranteed to work):
>
>	char *strdup(char *str)
>	{
>		char	*cp = (char *)malloc(strlen(str));
>		return cp ? strcpy(cp, str), cp : NULL;
>	}
>


Well it wont work. You've made the typical mistake of forgetting
about the '\0' at the end of the string. Make that "strlen(str)+1" in
the call to malloc() (and you can simplify the return statement a
little, strcpy() returns its first parameter so there's no need for
the comma operator).

-- 
Andy Newman (andy@research.canon.oz.au)		"int - God's own type"