Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 16 Dec 1996 21:25:18 -0700 (MST)
From:      Marc Slemko <marcs@znep.com>
To:        Jason Downs <downsj@teeny.org>
Cc:        freebsd-chat@freebsd.org
Subject:   snprintf vs. strncpy (was: Re: crontab security hole)
Message-ID:  <Pine.BSF.3.95.961216210309.10949D-100000@alive.ampr.ab.ca>
In-Reply-To: <199612170316.TAA22717@threadway.teeny.org>

next in thread | previous in thread | raw e-mail | index | archive | help
On Mon, 16 Dec 1996, Jason Downs wrote:

> It's bad programming practice to blindly use snprintf() without considering
> your options.  (Just as it's bad to use strncpy() without terminating the
> string yourself, or call strncat() with the wrong length.)

I think this discussion is far too sane.  Let's see who can make up the
most meaningless numbers.

marcs@alive:/tmp/str$ ls
snprintf	strncpy		strncpy-2.c
snprintf.c	strncpy-2	strncpy.c
marcs@alive:/tmp/str$ cat snprintf.c
#include <stdio.h>

int main () {
        char s[] = "jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj";
        char t[200];
        int c;

        for (c = 0; c < 500000; c++) {
                snprintf(t, sizeof(t), "%s", s);
        }
}

marcs@alive:/tmp/str$ cat strncpy.c
#include <string.h>

int main () {
        char s[] = "jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj";
        char t[200];
        int c;

        for (c = 0; c < 500000; c++) {
                strncpy(t, s, sizeof(t));
                t[sizeof(t)-1] = '\0';
        }
}

marcs@alive:/tmp/str$ cat strncpy-2.c
#include <string.h>

int main () {
        char s[] = "jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj";
        char t[200];
        int c;

        for (c = 0; c < 500000; c++) {
                strncpy(t, s, sizeof(t));
        }
}

marcs@alive:/tmp/str$ time ./snprintf ; time ./strncpy ; time ./strncpy-2
        6.86 real         5.65 user         0.02 sys
       11.50 real         9.85 user         0.00 sys
        9.54 real         9.15 user         0.01 sys
marcs@alive:/tmp/str$ 

Hmm.  Seems like snprintf is nearly twice as fast in this case.
What was that about considering your options?  Considering that we
already have sprintf in Vixie's code...

(No, I don't think snprintf is better than strncpy all the time, or
perhaps even most of the time but I don't see any reason to complain about
using snprintf instead of strncpy.  It is bad programming practice to do
_ANYTHING_ without considering your options.  What I do think is that we
need a freebsd-silly-numbers mailing list... I'm sure someone can reverse
these numbers for me.) 





Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?Pine.BSF.3.95.961216210309.10949D-100000>