incubator-stdcxx-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Martin Sebor <se...@roguewave.com>
Subject Re: [PATCH] rw_snprintf doesn't null terminate strings
Date Wed, 19 Dec 2007 02:44:57 GMT


Travis Vitek wrote:
> 
> 
> If rw_snprintf() is intended to behave like sprintf(), it should probably
> append the null terminator. If not, I should probably revise my fix to
> STDCXX-524 [https://issues.apache.org/jira/browse/STDCXX-524].
> 
> 

I think it should but the patch doesn't actually make it do that. I wrote a
small
test case to check (see below). here are the results with the patch:

rw_snprintf(0, "0123") ==> 4: "********"
snprintf   (0, "0123") ==> 4: "********"
rw_snprintf(1, "0123") ==> 4: "********"
snprintf   (1, "0123") ==> 4: "\0*******"
rw_snprintf(2, "0123") ==> 4: "********"
snprintf   (2, "0123") ==> 4: "0\0******"
rw_snprintf(3, "0123") ==> 4: "********"
snprintf   (3, "0123") ==> 4: "01\0*****"
rw_snprintf(4, "0123") ==> 4: "********"
snprintf   (4, "0123") ==> 4: "012\0****"
rw_snprintf(5, "0123") ==> 4: "0123\0***"
snprintf   (5, "0123") ==> 4: "0123\0***"
rw_snprintf(6, "0123") ==> 4: "0123\0***"
snprintf   (6, "0123") ==> 4: "0123\0***"

I committed a slightly different patch the does what I think we want:
http://svn.apache.org/viewvc?rev=605389&view=rev

Let me know if you see a problem with it.

Martin



> 
> Travis 
> 
> 
> Index: printf.cpp
> ===================================================================
> --- printf.cpp	(revision 605328)
> +++ printf.cpp	(working copy)
> @@ -3376,8 +3376,10 @@
>  
>      va_end (va);
>  
> -    if (size_t (nchars) <= bufsize)
> +    if (size_t (nchars) < bufsize) {
>          memcpy (buf, tmpbuf, size_t (nchars));
> +        buf [nchars] = 0;
> +    }
>  
>      free (tmpbuf);
> 

#include <rw_printf.h>
#include <stdio.h>

void test (int n, const char *s)
{
    char buf1[8] = { '*', '*', '*', '*', '*', '*', '*', '*' };
    char buf2[8] = { '*', '*', '*', '*', '*', '*', '*', '*' };

    int m;
    
    m = rw_snprintf (buf1, n, s);
    rw_printf ("rw_snprintf(%d, %#s) ==> %d: %{#*s}\n",
               n, s, m, int (sizeof buf1), buf1);

    m = snprintf (buf2, n, s);
    rw_printf ("snprintf   (%d, %#s) ==> %d: %{#*s}\n",
               n, s, m, int (sizeof buf2), buf2);
}

int main ()
{
    test (0, "0123");
    test (1, "0123");
    test (2, "0123");
    test (3, "0123");
    test (4, "0123");
    test (5, "0123");
    test (6, "0123");
}

-- 
View this message in context: http://www.nabble.com/-PATCH--rw_snprintf-doesn%27t-null-terminate-strings-tp14407607p14410127.html
Sent from the stdcxx-dev mailing list archive at Nabble.com.


Mime
View raw message