zoukankan      html  css  js  c++  java
  • strcpy/strncpy、strcat/strncpy的替代方案strlcpy,strlcat

    strlcat.c

    #include <sys/types.h>
    #include <string.h>
    
    /*
     * Appends src to string dst of size dsize (unlike strncat, dsize is the
     * full size of dst, not space left).  At most dsize-1 characters
     * will be copied.  Always NUL terminates (unless dsize <= strlen(dst)).
     * Returns strlen(src) + MIN(dsize, strlen(initial dst)).
     * If retval >= dsize, truncation occurred.
     */
    size_t
    strlcat(char *dst, const char *src, size_t dsize)
    {
        const char *odst = dst;
        const char *osrc = src;
        size_t n = dsize;
        size_t dlen;
    
        /* Find the end of dst and adjust bytes left but don't go past end. */
        while (n-- != 0 && *dst != '\0')
            dst++;
        dlen = dst - odst;
        n = dsize - dlen;
    
        if (n-- == 0)
            return(dlen + strlen(src));
        while (*src != '\0') {
            if (n != 0) {
                *dst++ = *src;
                n--;
            }
            src++;
        }
        *dst = '\0';
    
        return(dlen + (src - osrc));    /* count does not include NUL */
    }

    测试代码 strlcattest.c

    #include <sys/types.h>
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <setjmp.h>
    #include <signal.h>
    #include <unistd.h>
    
    volatile sig_atomic_t got_signal;
    sigjmp_buf jmpenv;
    
    void
    handler(int signo)
    {
            got_signal = signo;
        siglongjmp(jmpenv, 1);
    }
    
    int
    main(int argc, char *argv[])
    {
        char *buf, *cp, *ep;
        struct sigaction sa;
        size_t len, bufsize;
        int failures = 0;
    
        bufsize = getpagesize(); /* trigger guard pages easily */
        buf = malloc(bufsize);
        if (buf == NULL) {
            fprintf(stderr, "unable to allocate memory\n");
            return 1;
        }
        memset(buf, 'z', bufsize);
        ep = buf + bufsize;
    
        /* Test appending to an unterminated string. */
        len = strlcat(buf, "abcd", bufsize);
        if (len != 4 + bufsize) {
            fprintf(stderr,
                "strlcat: failed unterminated buffer test (1a)\n");
            failures++;
        }
        /* Make sure we only wrote where expected. */
        for (cp = buf; cp < ep; cp++) {
            if (*cp != 'z') {
                fprintf(stderr,
                    "strlcat: failed unterminated buffer test (1b)\n");
                failures++;
                break;
            }
        }
    
        /* Test appending to a full string. */
        ep[-1] = '\0';
        len = strlcat(buf, "abcd", bufsize);
        if (len != 4 + bufsize - 1) {
            fprintf(stderr, "strlcat: failed full buffer test (2a)\n");
            failures++;
        }
        /* Make sure we only wrote where expected. */
        for (cp = buf; cp < ep - 1; cp++) {
            if (*cp != 'z') {
                fprintf(stderr,
                    "strlcat: failed full buffer test (2b)\n");
                failures++;
                break;
            }
        }
    
        /* Test appending to an empty string. */
        ep[-1] = 'z';
        buf[0] = '\0';
        len = strlcat(buf, "abcd", bufsize);
        if (len != 4) {
            fprintf(stderr, "strlcat: failed empty buffer test (3a)\n");
            failures++;
        }
        /* Make sure we only wrote where expected. */
        if (memcmp(buf, "abcd", sizeof("abcd")) != 0) {
            fprintf(stderr, "strlcat: failed empty buffer test (3b)\n");
            failures++;
        }
        for (cp = buf + len + 1; cp < ep; cp++) {
            if (*cp != 'z') {
                fprintf(stderr,
                    "strlcat: failed empty buffer test (3c)\n");
                failures++;
                break;
            }
        }
    
        /* Test appending to a NUL-terminated string. */
        memcpy(buf, "abcd", sizeof("abcd"));
        len = strlcat(buf, "efgh", bufsize);
        if (len != 8) {
            fprintf(stderr, "strlcat: failed empty buffer test (4a)\n");
            failures++;
        }
        /* Make sure we only wrote where expected. */
        if (memcmp(buf, "abcdefgh", sizeof("abcdefgh")) != 0) {
            fprintf(stderr, "strlcat: failed empty buffer test (4b)\n");
            failures++;
        }
        for (cp = buf + len + 1; cp < ep; cp++) {
            if (*cp != 'z') {
                fprintf(stderr,
                    "strlcat: failed empty buffer test (4c)\n");
                failures++;
                break;
            }
        }
    
            /*
             * The following tests should result in SIGSEGV, however some
             * systems may erroneously report SIGBUS.
             * These tests assume that strlcat() is signal-safe.
             */
            memset(&sa, 0, sizeof(sa));
            sigemptyset(&sa.sa_mask);
            sa.sa_handler = handler;
            sigaction(SIGSEGV, &sa, NULL);
            sigaction(SIGBUS, &sa, NULL);
    
            /* Test copying to a NULL buffer with non-zero size. */
            got_signal = 0;
            if (sigsetjmp(jmpenv, 1) == 0) {
                    len = strlcat(NULL, "abcd", sizeof(buf));
                    fprintf(stderr, "strlcat: failed NULL dst test (5a), "
                        "expected signal %d, got len %zu\n", SIGSEGV, len);
                    failures++;
            } else if (got_signal != SIGSEGV) {
                    fprintf(stderr, "strlcat: failed NULL dst test (5b), "
                        "expected signal %d, got %d\n", SIGSEGV, got_signal);
                    failures++;
            }
    
            /* Test copying from a NULL src. */
        memcpy(buf, "abcd", sizeof("abcd"));
            got_signal = 0;
            if (sigsetjmp(jmpenv, 1) == 0) {
                    len = strlcat(buf, NULL, sizeof(buf));
                    fprintf(stderr, "strlcat: failed NULL src test (6a), "
                        "expected signal %d, got len %zu\n", SIGSEGV, len);
                    failures++;
            } else if (got_signal != SIGSEGV) {
                    fprintf(stderr, "strlcat: failed NULL src test (6b), "
                        "expected signal %d, got %d\n", SIGSEGV, got_signal);
                    failures++;
            }
    
        return failures;
    }

    strlcpy.c

    #include <sys/types.h>
    #include <string.h>
    
    /*
     * Copy string src to buffer dst of size dsize.  At most dsize-1
     * chars will be copied.  Always NUL terminates (unless dsize == 0).
     * Returns strlen(src); if retval >= dsize, truncation occurred.
     */
    size_t
    strlcpy(char *dst, const char *src, size_t dsize)
    {
        const char *osrc = src;
        size_t nleft = dsize;
    
        /* Copy as many bytes as will fit. */
        if (nleft != 0) {
            while (--nleft != 0) {
                if ((*dst++ = *src++) == '\0')
                    break;
            }
        }
    
        /* Not enough room in dst, add NUL and traverse rest of src. */
        if (nleft == 0) {
            if (dsize != 0)
                *dst = '\0';        /* NUL-terminate dst */
            while (*src++)
                ;
        }
    
        return(src - osrc - 1);    /* count does not include NUL */
    }

    测试代码strlcpy.c

    /*    $OpenBSD: strlcpytest.c,v 1.4 2021/09/01 09:26:32 jasper Exp $ */
    
    /*
     * Copyright (c) 2014 Todd C. Miller <millert@openbsd.org>
     *
     * Permission to use, copy, modify, and distribute this software for any
     * purpose with or without fee is hereby granted, provided that the above
     * copyright notice and this permission notice appear in all copies.
     *
     * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     */
    
    #include <sys/types.h>
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <signal.h>
    #include <setjmp.h>
    #include <unistd.h>
    
    volatile sig_atomic_t got_signal;
    sigjmp_buf jmpenv;
    
    void
    handler(int signo)
    {
        got_signal = signo;
        siglongjmp(jmpenv, 1);
    }
    
    int
    main(int argc, char *argv[])
    {
        char *buf, *buf2, *cp, *ep;
        struct sigaction sa;
        size_t len, bufsize;
        int failures = 0;
    
        bufsize = getpagesize(); /* trigger guard pages easily */
        buf = malloc(bufsize);
        buf2 = malloc(bufsize);
        if (buf == NULL || buf2 == NULL) {
            fprintf(stderr, "unable to allocate memory\n");
            return 1;
        }
        memset(buf, 'z', bufsize);
        ep = buf + bufsize;
    
        /* Test copying to a zero-length NULL buffer. */
        len = strlcpy(NULL, "abcd", 0);
        if (len != 4) {
            fprintf(stderr,
                "strlcpy: failed zero-length buffer test (1a)\n");
            failures++;
        }
    
        /* Test copying small string to a large buffer. */
        len = strlcpy(buf, "abcd", bufsize);
        if (len != 4) {
            fprintf(stderr, "strlcpy: failed large buffer test (2a)\n");
            failures++;
        }
        /* Make sure we only wrote where expected. */
        if (memcmp(buf, "abcd", sizeof("abcd")) != 0) {
            fprintf(stderr, "strlcpy: failed large buffer test (2b)\n");
            failures++;
        }
        for (cp = buf + len + 1; cp < ep; cp++) {
            if (*cp != 'z') {
                fprintf(stderr,
                    "strlcpy: failed large buffer test (2c)\n");
                failures++;
                break;
            }
        }
    
        /* Test copying large string to a small buffer. */
        memset(buf, 'z', bufsize);
        memset(buf2, 'x', bufsize - 1);
        buf2[bufsize - 1] = '\0';
        len = strlcpy(buf, buf2, bufsize / 2);
        if (len != bufsize - 1) {
            fprintf(stderr, "strlcpy: failed small buffer test (3a)\n");
            failures++;
        }
        /* Make sure we only wrote where expected. */
        len = (bufsize / 2) - 1;
        if (memcmp(buf, buf2, len) != 0 || buf[len] != '\0') {
            fprintf(stderr, "strlcpy: failed small buffer test (3b)\n");
            failures++;
        }
        for (cp = buf + len + 1; cp < ep; cp++) {
            if (*cp != 'z') {
                fprintf(stderr,
                    "strlcpy: failed small buffer test (3c)\n");
                failures++;
                break;
            }
        }
    
        /* Test copying to a 1-byte buffer. */
        memset(buf, 'z', bufsize);
        len = strlcpy(buf, "abcd", 1);
        if (len != 4) {
            fprintf(stderr, "strlcpy: failed 1-byte buffer test (4a)\n");
            failures++;
        }
        /* Make sure we only wrote where expected. */
        if (buf[0] != '\0') {
            fprintf(stderr, "strlcpy: failed 1-byte buffer test (4b)\n");
            failures++;
        }
        for (cp = buf + 1; cp < ep; cp++) {
            if (*cp != 'z') {
                fprintf(stderr,
                    "strlcpy: failed 1-byte buffer test (4c)\n");
                failures++;
                break;
            }
        }
    
        /*
         * The following tests should result in SIGSEGV, however some
         * systems may erroneously report SIGBUS.
         * These tests assume that strlcpy() is signal-safe.
         */
        memset(&sa, 0, sizeof(sa));
        sigemptyset(&sa.sa_mask);
        sa.sa_handler = handler;
        sigaction(SIGSEGV, &sa, NULL);
        sigaction(SIGBUS, &sa, NULL);
    
        /* Test copying to a NULL buffer with non-zero size. */
        got_signal = 0;
        if (sigsetjmp(jmpenv, 1) == 0) {
            len = strlcpy(NULL, "abcd", sizeof(buf));
            fprintf(stderr, "strlcpy: failed NULL dst test (5a), "
                "expected signal %d, got len %zu\n", SIGSEGV, len);
            failures++;
        } else if (got_signal != SIGSEGV) {
            fprintf(stderr, "strlcpy: failed NULL dst test (5b), "
                "expected signal %d, got %d\n", SIGSEGV, got_signal);
            failures++;
        }
    
        /* Test copying from a NULL src. */
        got_signal = 0;
        if (sigsetjmp(jmpenv, 1) == 0) {
            len = strlcpy(buf, NULL, sizeof(buf));
            fprintf(stderr, "strlcpy: failed NULL src test (6a), "
                "expected signal %d, got len %zu\n", SIGSEGV, len);
            failures++;
        } else if (got_signal != SIGSEGV) {
            fprintf(stderr, "strlcpy: failed NULL src test (6b), "
                "expected signal %d, got %d\n", SIGSEGV, got_signal);
            failures++;
        }
    
        return failures;
    }

    代码来源:http://ftp.openbsd.org/pub/OpenBSD/7.0/src.tar.gz

    本博客文章绝大多数为原创,少量为转载,代码经过测试验证,如果有疑问直接留言或者私信我。
    创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。
  • 相关阅读:
    windows设置自动登录
    windows zabbix agent
    同时给AD用户加入多个组
    zabbix监控DELL戴尔idrac卡
    Windows安装Zabbix Agent
    各服务器厂商默认密码
    AD域管理命令工具
    linux服务五——rsync 服务部署详解
    linux服务四——SSH服务详解
    LINUX核心命令实战总结十三——系统常用内置命令
  • 原文地址:https://www.cnblogs.com/passedbylove/p/15545965.html
Copyright © 2011-2022 走看看