[Top][All Lists]

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

Re: printf precision with NULL-terminated strings

From: Andreas Jaeger
Subject: Re: printf precision with NULL-terminated strings
Date: Mon, 14 Feb 2005 09:10:04 +0100
User-agent: Gnus/5.110003 (No Gnus v0.3) XEmacs/21.4.15 (linux)

"Ben Love" <address@hidden> writes:

> Hello,
> 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);

a is not nul-terminated and therefore not a proper string argument,


> }
> 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?
> Sincerely,
> Ben Love
> _______________________________________________
> Bug-glibc mailing list
> address@hidden
> http://lists.gnu.org/mailman/listinfo/bug-glibc

 Andreas Jaeger, address@hidden, http://www.suse.de/~aj
  SUSE LINUX Products GmbH, Maxfeldstr. 5, 90409 N├╝rnberg, Germany
   GPG fingerprint = 93A3 365E CE47 B889 DF7F  FED1 389A 563C C272 A126

Attachment: pgpsQ3bOlLbXF.pgp
Description: PGP signature

reply via email to

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