strncpy

John Mundt john at chinet.chi.il.us
Sun Dec 24 11:20:04 AEST 1989


In article <8313 at stiatl.UUCP> cns at stiatl.UUCP (Chris Straut) writes:
>In article <11509 at csli.Stanford.EDU> poser at csli.Stanford.EDU (Bill Poser) writes:
>>	Why is it that strncpy(3) does not null terminate
>>the string if the length of the source string is greater than
>>or equal to the length of the target buffer? 
>                 [ other stuff deleted ]
>
>
>I agree that strncpy should null terminate the resulting string.  The 
>definition of a string in the C language is a null terminated char array.
>And the function called (str)ncpy indicates a string operation, which by
>default should create a null terminated string.  To overcome this 'feature'
>we wrote our own strncpy function, which is benefical to the unsuspecting
>programmer (or novice), and the result is a null terminated string.

C has allowed you to shoot yourself in the foot if you want to.  And the
man page clearly says that the string is not null terminated if it runs
to the full length permitted by the integer argument.

Good reasons abound.  For example, if you wish to replace a *part* of
a string with something else, strncpy allows you to do that.  Having
an terminating \0 stuck in there would truncate the string and wipe
out a character.  You'd have to do some fancy footwork to get the
tail end of the string stuck on the end in such a situation.  

Not to mention that with the length known, it is easy as pie
to null terminate the string if necessary:

#defind LENGTH 10

some_func(s1)
char *s1;
{
char buf[500];
	buf[LENGTH] = '\0';
	(void)strncpy(buf, s1, LENGTH);
}
-- 
---------------------
John Mundt   Teachers' Aide, Inc.  P.O. Box 1666  Highland Park, IL
john at admctr.chi.il.us *OR* fred at teacha.chi.il.us
(312) 998-5007 (Day voice) || -432-8860 (Answer Mach) && -432-5386 Modem  



More information about the Comp.lang.c mailing list