Mail Archives: geda-user/2023/02/02/18:11:41
DJ Delorie:
> "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.
Well, add a dst[sizeof(dst)-1] = '\0' then.
> 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.
should it handle overlapping strings ?
> 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()
> }
I'm not found of abort(). It's ok if you are developing, else you should
fail gracefully.
int pcb_strcpy(src, dst, dsz) {
if (!dst || !dsz) return -1;
if (!src) return 0;
size_t src_len = strlen(src);
if (src_len+1 > dsz) return -2;
if (src < dst && src+src_len >= dst) return -3;
if (dst+src_len+1 >= src) return -4;
memcpy(src,dst,src_len+1);
return src_len;
}
Then one needs some support to handle return values.
My take on that is:
https://aspodata.se/git/c/libaspoutil/log_util.h
Regards,
/Karl Hammar
- Raw text -