What defines strscpy in C?

2.3k Views Asked by At

From this video on youtube by Kees Cook from linux.conf.au 2019 he mentions strscpy as being preferred but generally doing what users want (less NUL-padding). However, he doesn't say what defines this (spec or header),

Slide from the video,

strscpy slide

I can't find strscpy() with man

$ for i in strcpy strlcpy strscpy; do man -w $i; done;
/usr/share/man/man3/strcpy.3.gz
/usr/share/man/man3/strlcpy.3bsd.gz
No manual entry for strscpy
2

There are 2 best solutions below

2
AShelly On BEST ANSWER

It's in the linux source, not in the standard library. Online man page

0
alx - recommends codidact On

Given that there isn't any library that provides this function (AFAIK), you can write it yourself. I'm sure it can be optimized, but a very simple definition using GNU C11 for it is this one, which I use:

#pragma once    /* libalx/base/string/strcpy/strscpy.h */


#include <stddef.h>


__attribute__((nonnull))
ptrdiff_t strscpy       (char dest[restrict /*size*/],
                         const char src[restrict /*size*/],
                         ptrdiff_t size);
#include "libalx/base/string/strcpy/strscpy.h"

#include <errno.h>
#include <stddef.h>
#include <string.h>


ptrdiff_t strscpy       (char dest[restrict /*size*/],
                         const char src[restrict /*size*/],
                         ptrdiff_t size)
{
        ptrdiff_t   len;

        if (size <= 0)
                return  -E2BIG;

        len     = strnlen(src, size - 1);
        memcpy(dest, src, len);
        dest[len] = '\0';

        return  len;
}

Note: I prefer ptrdiff_t for array sizes, but you can use size_t/ssize_t as the linux version does.