----- Original Message ----- 
From: "tweety" 
To: 
Sent: Thursday, May 06, 2004 2:03 AM
Subject: RE: [c-prog] binary trees


> why did you use strncpy to copy *8* characters if you're going to chop off
> the last one, anyway?
>  
> oh, and since this is my first post, hi all!
>  
> ----------------------------------
> Peace and love,
> Tweety 
>

 From: Vijay Kumar R Zanvar [mailto:vijaykumar.rz@globaledgesoft.com] 
 Sent: May 5, 2004 6:58 AM
 To: c-prog@yahoogroups.com
 Subject: Re: [c-prog] binary trees
 
>> 
>> void
>> attach ( tree_t **ptr, const char *name )
>> { 
>>     if ( !*ptr )
>>     {
>>         *ptr = malloc ( sizeof **ptr ); 
>>         if ( ptr )
>>         {
>>             memset ( *ptr, 0, sizeof **ptr );
>>             strncpy ( (*ptr) -> name, name, 8 );
>>           /* strncpy() is not usually preferred, because it has some
>> limitations */    
>>             (*ptr) -> name[7] = '\0'; 
>>         }
>>         return;
>>     }
>>     else
>>     if ( strcmp ( (*ptr) -> name, name ) > 0 )
>>         attach ( &(*ptr) -> left, name );
>>     else
>>     if ( strcmp ( (*ptr) -> name, name ) < 0 )
>>         attach ( &(*ptr) -> right, name );
>> }
>> 

There are two precautions that the programmer must take while using strncpy().  

    +   char * strncpy ( char *s, const char *t, size_t n );

    +   strncpy() will NOT copy NUL if strlen(t) >= n.  This can become 
        dangerous if the programmer does not take care.  Which why I explicitly
        wrote:

            (*ptr) -> name[7] = '\0'; 

    +   If strlen(t) < n, then NUL will be appended until all n characters have
        been written.  A computation-conscious programmer will note that for
        a large value of n and a small value of strlen(t), strncpy() will take
        more time than strcpy().  (However, with today's multi-gigahertz CPUs,
        who really notices?)
    
    Following program is an extract from:
    http://www.geocities.com/vijoeyz/faq/knr/5/5-5.html

/*
 * 5-5.c       
 * Author:  Vijay Kumar R Zanvar 
 *  About:  Library versions of strncpy, strncat, strncmp
 *   Date:  Jan 13, 2004
 */

#include 
#include 

char *
strncpy ( char *s, const char *t, size_t n )
{
    char * const p = s;

    if ( !s || !t )
        return s;

    while ( *t && n )
    {
        *s++ = *t++;
        n--;
    }

    if ( n )
    {
        do 
            *s++ = '\0';
        while ( --n );
    }
    return p;
}
 

    Source: geocities.com/vijoeyz/faq/c

               ( geocities.com/vijoeyz/faq)                   ( geocities.com/vijoeyz)