www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/09/24/14:51:03

Date: Wed, 24 Sep 1997 14:47:48 -0400 (EDT)
From: "Art S. Kagel" <kagel AT ns1 DOT bloomberg DOT com>
To: "Peter J. Farley III" <pjfarley AT dorsai DOT org>
Cc: djgpp AT delorie DOT com
Subject: Re: Problem with strncpy (DJGPP in msdos window in win95)
In-Reply-To: <342864fb.2276250@snews.zippo.com>
Message-Id: <Pine.D-G.3.91.970924144033.7569B-100000@dg1>
Mime-Version: 1.0

On Wed, 24 Sep 1997, Peter J. Farley III wrote:

> "Paul Fitzgibbons" <pfitzg AT mail DOT csc DOT liv DOT ac DOT uk> wrote:
> <Snipped>
> >I have a problem with the following code. When inputting strings of up to 20
> >chars there doesnt appear to be a problem but if i input a string of length
> >21 or greater the string then ends in funny characters. I thought strncpy
> >would have avoided this? I am able to write a function to check if the
> >length is greater and to loop if it is, but i would rather do it by
> >shortening the string.
> >
> >Any help will be much appreciated.
> 
> Paul,
> 
> You forgot to terminate the string.  IIRC, strncpy() does not
> terminate with a null after the "n" characters are copied.  Try this
> (see my added comments).  Output examples following the code.

Almost, strncpy copies up to n characters including any NULL that it
finds in those first n characters and then pads the target string with
NULLS to 'n' characters (I have a friend who uses strncpy("",mystr,20)
to initialize string spaces to NULLs, slower than memset() but he has
fun...).  So, just as Paul noticed, if the source string is longer
than 'n' characters the target is not NULL terminated.  Peter's
recommended code is correct, very standard (I do it that way myself),
and very efficient (the, perhaps unneccessary assignment is a lot
cheaper than the test that could eliminate it).

Art S. Kagel, kagel AT bloomberg DOT com

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019