char str[] = "some text"; printf ( "%.*s", strlen(str), str );
** Of course, their buffers, strings yet to be properly targeted
char str[] = "some text"; printf ( "%.*s", strlen(str), str );
** Of course, their buffers, strings yet to be properly targeted
No, printf should be safe form overruns anyway setting a field width doesn't really help
No, that just shifts the problem of detecting the end of the string from printf to strlen, and it's still exactly the same.
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
.
No, it's no different than:
char str[] = "some text";
printf("%s", str);