cvs.gedasymbols.org/archives/browse.cgi   search  
Mail Archives: djgpp/1997/10/25/01:17:01

Date: Fri, 24 Oct 1997 22:13:31 -0700 (PDT)
Message-Id: <199710250513.WAA07748@adit.ap.net>
Mime-Version: 1.0
To: Brett Porter <bporter AT rabble DOT uow DOT edu DOT au>, djgpp AT delorie DOT com (DJGPP)
From: Nate Eldredge <eldredge AT ap DOT net>
Subject: Re: strncpy question

At 12:21  10/24/1997 +1000, Brett Porter wrote:
>Here is something strange I have encountered using DJGPP...
>
>I use this code in C++, where fName is a char* and aName is const char*
>
>fName = new char[strlen(aName)+1];
>strncpy( fName, aName, 74 );
>
>I don't want anymore than 74 characters to be displayed when I cprintf(
>fName ), because it goes to the text mode screen, so I do this and also put
>a zero at fName[74] (if the string length is that long)
>
>It started to overwrite other memory.
>I realise what I had done here was bad coding, and I've fixed it up, but I
>was curious what was going on here. IS the definition of strncpy in DJGPP to
>zero out up to the limit specified, or does it stop at the NULL character? I
>thought it was the latter but this example would seem to indicate otherwise.
strncpy(s1,s2,n) will copy up to `n' characters from `s2' to `s1'. If it
finds a NUL ('\0') in the input, it stops copying and pads `s1' with NUL's
up to `n' bytes. If it does not find a NUL, it copies `n' bytes, but *does
not* NUL terminate s1.
Here are some examples, assume "dest" is a big-enough buffer:
strncpy(dest,"Hello",10);
--> dest == "Hello\0\0\0\0\0"
strncpy(dest,"Hello",3);
--> dest == "Hel" (no null terminator)

Btw, I found this by looking at the strncpy source. This is never a bad
approach to answering a question like "What does X do?"

Nate Eldredge
eldredge AT ap DOT net



- Raw text -


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