delorie.com/archives/browse.cgi   search  
Mail Archives: geda-user/2023/02/02/12:54:01

X-Authentication-Warning: delorie.com: mail set sender to geda-user-bounces using -f
X-Authentication-Warning: envy.delorie.com: dj set sender to dj AT delorie DOT com using -f
From: DJ Delorie <dj AT delorie DOT com>
To: geda-user AT delorie DOT com
Subject: Re: [geda-user] strncpy in pcb
In-Reply-To: <20230202154018.8BD4085E50B5@turkos.aspodata.se>
(geda-user AT delorie DOT com)
Date: Thu, 02 Feb 2023 12:34:34 -0500
Message-ID: <xn7cx02cph.fsf@envy.delorie.com>
MIME-Version: 1.0
Reply-To: geda-user AT delorie DOT com
Errors-To: nobody AT delorie DOT com
X-Mailing-List: geda-user AT delorie DOT com
X-Unsubscribes-To: listserv AT delorie DOT com

"karl AT aspodata DOT se [via geda-user AT delorie DOT com]" <geda-user AT delorie DOT com>
writes:
> Generally, it would be best to use the form:
>  strncpy(dst,src,sizeof(dst)-1)

The problem with strncpy is that it doesn't always NUL-terminate the
destination, even in the case above.  If the source string length
happens to be the same as the specified size, no NUL is written, you
have a non-terminated string, and it's a security issue assuming it
doesn't just crash.

What is needed is a function that:

1. Copies the whole string, including NUL, if it fits, or

2. Fails safely if it doesn't.

strncpy can't be made to do that.  Neither can strlcpy for that matter.
strcpy_s can but it isn't generally available yet.

What we need is something like:

pcb_strcpy (s, d, l)
{
  i = strlen(s);
  if (i+1 <= l)
    memcpy (s, d, i+1)
  else
    abort()
}

- Raw text -


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