views:

66

answers:

4
char str[] = "some text";

printf ( "%.*s", strlen(str), str );

** Of course, their buffers, strings yet to be properly targeted

+1  A: 

No, printf should be safe form overruns anyway setting a field width doesn't really help

Martin Beckett
+3  A: 

No, that just shifts the problem of detecting the end of the string from printf to strlen, and it's still exactly the same.

Roger Pate
printf does not attempt to detect the end of the buffer.
Billy ONeal
@Billy: printf attempts to detect the end of the string (the logical value, not the end of the buffer) by looking for a null character.
Roger Pate
@Roger Pate: Sorry .. was thinking sprintf :)
Billy ONeal
+2  A: 

In the example you give, there's no difference. printf interprets the undecorated "%s" character code as meaning "read and print all characters from a character pointer until a null character is encountered." The initializer char str[] = "some text"; automatically appends the null character, so there will be no overrun. On the other hand, the following is not safe

char str[] = {'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'};
printf("%s", str);

because no null character is appended to the character sequence str. On the other hand, since strlen(str) determines string length by counting the number of characters before a null is encountered, it doesn't offer you any benefit over just using printf without a field width specified.

The upshot: the only case where specifying a field width for a string is helpful is when the string isn't guaranteed to be null-terminated (or the classic case of using sprintf to write to a buffer that may not be big enough to hold the contents of str), but in that case you'd have to determine string length using something other than strlen.

Dathan
A: 

No, it's no different than:

char str[] = "some text";
printf("%s", str);
Andrew Medico