www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/09/26/23:46:22

From: "Mark S. Novojilov" <novojilo AT explorer DOT uni-trier DOT de>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Problem with strncpy (DJGPP in msdos window in win95)
Date: Wed, 24 Sep 1997 22:40:16 +0200
Organization: Universitaet Trier
Lines: 77
Message-ID: <34297AAF.7E7C62A6@explorer.uni-trier.de>
References: <EGwqnM DOT 2v2 AT csc DOT liv DOT ac DOT uk>
NNTP-Posting-Host: sliphost4177.uni-trier.de
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Paul Fitzgibbons wrote:

> Hi there
>
> just like to say that I am enjoying learning with DJGPP and have also got
> the Allegro Library from Shawn Hargreaves.
>
> 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.
>
> Many thanks Paul Fitz
>
> [code follows]
>
> #include <stdio.h>
> #include <string.h>
> #include <stdlib.h>
>
> struct DETAIL
> {
>    char name[21]; //max length +1 for NULL
> };
>
> void dispstru(struct DETAIL *ptr);
>
> main()
> {
>    struct DETAIL Personal_info;
>    struct DETAIL *Personal_info_ptr;
>    char buff[1024];  //nice and long to avoid errors

but still don't guarantee from an error ;-)

>
>
>    printf("What is the name? : ");
>    gets(buff);
>
>    strncpy(Personal_info.name,buff,20); //copy 20 chars
>

Here, a copy from man page on strncpy:...
      The  strncpy()  function  is similar, except that not more
       than n bytes of src are copied. Thus, if there is no  null
       byte among the first n bytes of src, the result wil not be
       null-terminated.

       In the case where the length of src is less than  that  of
       n, the remainder of dest will be padded with nulls.

So to correct your problem you just add at this place:
Personal_info.name[20]='\0';         and that's it.
But there's another solution of this problem, without
using additional buff[1024] : using fgets
fgets(Personal_info.name,21,stdin);
Advantage: only one futnction call, no additional buf and it's always safe.

>    printf("name is : %s",Personal_info.name);
>
>    Personal_info_ptr=&Personal_info;
>    dispstru(Personal_info_ptr);
> }
>
> void dispstru(struct DETAIL *ptr)
> {
>    printf("Pointer to name = : %s ",ptr->name);
> }

                    - Mark


- Raw text -


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