git/list[1] front-page[2] threads[3] people[4] search[5] about
 

Re: [PATCH] Make xstrndup common

From
Daniel Barkalow <barkalow@iabervon.org>
Date
May 3, 2007, 05:02 UTC
Message-ID
<Pine.LNX.4.64.0705030100050.28708@iabervon.org>
In-Reply-To
<7vzm4m35xm.fsf@assigned-by-dhcp.cox.net>
On Wed, 2 May 2007, Junio C Hamano wrote:
Show 54 quoted lines
> Daniel Barkalow <barkalow@iabervon.org> writes:
> 
> > This also improves the implementation to match how strndup is
> > specified (by GNU): if the length given is longer than the string,
> > only the string's length is allocated and copied, but the string need
> > not be null-terminated if it is at least as long as the given length.
> >
> > Signed-off-by: Daniel Barkalow <barkalow@iabervon.org>
> > ---
> > Haven't got the rest of my series updated for comments, but I'd like to 
> > get this change, which is logically unrelated aside from being a 
> > dependancy, in now.
> >
> >  commit.c          |    8 --------
> >  git-compat-util.h |   12 ++++++++++++
> >  2 files changed, 12 insertions(+), 8 deletions(-)
> >
> > diff --git a/commit.c b/commit.c
> > index f1ba972..aa7059c 100644
> > --- a/commit.c
> > +++ b/commit.c
> > @@ -718,14 +718,6 @@ static char *logmsg_reencode(const struct commit *commit,
> >  	return out;
> >  }
> >  
> > -static char *xstrndup(const char *text, int len)
> > -{
> > -	char *result = xmalloc(len + 1);
> > -	memcpy(result, text, len);
> > -	result[len] = '\0';
> > -	return result;
> > -}
> > -
> >  static void fill_person(struct interp *table, const char *msg, int len)
> >  {
> >  	int start, end, tz = 0;
> > diff --git a/git-compat-util.h b/git-compat-util.h
> > index 2c84016..0dcd4e2 100644
> > --- a/git-compat-util.h
> > +++ b/git-compat-util.h
> > @@ -197,6 +197,18 @@ static inline void *xmalloc(size_t size)
> >  	return ret;
> >  }
> >  
> > +static inline char *xstrndup(const char *str, int len)
> > +{
> > +	char *ret;
> > +	int i;
> > +	for (i = 0; i < len && str[i]; i++)
> > +		;
> > +	ret = xmalloc(i + 1);
> > +	strncpy(ret, str, i);
> 
> Why strncpy() not memcpy()?

Left over from my previous attempt. memcpy() is better with the length check.

	-Daniel
*This .sig left intentionally blank*
Previous: Junio C HamanoNext: Junio C Hamano
Message 3 of 6 in “Make xstrndup common”
  1. Make xstrndup commonDaniel Barkalow, May 3, 2007
  2. Junio C HamanoMay 3, 2007
  3. Daniel BarkalowMay 3, 2007
  4. Junio C HamanoMay 3, 2007
  5. Alex RiesenMay 3, 2007
  6. Junio C HamanoMay 4, 2007

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.