[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

printf precision with NULL-terminated strings

From: Ben Love
Subject: printf precision with NULL-terminated strings
Date: Fri, 11 Feb 2005 05:40:34 -0800


It appears that using a precision to limit the number of
characters printed from a string may read more characters
from the string than was specified.  I wondered if this was
expected behavior.  Here is a sample program:

int main(int argc, char **argv)
   char a* = malloc(7);
   memcpy(a, "1234567", 7);
   printf("%.*s", 6, a);

The output is (as expected) "123456".

However, when run with 'valgrind --tool=addrcheck a.out'
I see the following error message:

Invalid read of size 1
   at 0x341CCCAE: strnlen (in /lib/libc-2.3.2.so)
   by 0x341A0383: _IO_vfprintf (in /lib/libc-2.3.2.so)
   by 0x341A68D1: _IO_printf (in /lib/libc-2.3.2.so)
   by 0x8048418: main (/root/test_app/a.out)
 Address 0x3428B02F is 0 bytes after a block of size 7 alloc'd
   at 0x3414A5C1: malloc (vg_replace_malloc.c:131)
   by 0x80483DF: main (/root/test_app/a.out)

At first, I thought maybe it was a word-alignment problem,
where printf was reading 4 bytes at a time.  However, when
you replace the memcpy line with this one:
   memcpy(a, "123456\0", 7);
(i.e., force a NULL earlier) valgrind detects no overrun.
It appears that printf continues to read from the string
until the NULL terminating character is found, and only
then does it limit the output to the number of characters
specified.  According to the manpage: "If a precision is
given, no null character need be present."

Any thoughts?  Is this behavior to be expected?

Ben Love

reply via email to

[Prev in Thread] Current Thread [Next in Thread]