3 ms·
The %.* example is so close to hitting its single most useful application: char *something; /* no null termination */ size_t something_length; printf("
by eqvinox 3y ago
The %.* example is so close to hitting its single most useful application:
char *something; /* no null termination */
size_t something_length;
printf("%.*s", (int)something_length, something);
Unfortunately, the .* argument has type (int), not size_t, and it's signed… but if that's not a problem this is a great way to format non-\0-terminated strings.
(And of course you can also use it to print a substring without copying it around first.)
- jrpelkonen 3y agoIn this simple case, if the int cast is a problem, fwrite would be an adequate alternative, don’t you think?
- PaulDavisThe1st 3y agonot for s(n)printf ...
- LegionMammal978 3y agoFor that, the analogue would be memcpy; but both alternatives lose the ease of surrounding the string with other text, since you either have to do the length calculations or define helper functions.
- eqvinox 3y agoThe point of this is that you can use it in format strings where you may be printing a whole bunch of other things. In particular there are some APIs where you need to submit the whole format/string in one go, an example from libc is syslog(), but other libraries do this as well occasionally.
- thaliaarchi 3y agoSomewhat related to this, printf alone in a loop is Turing-complete, by using %-directives like that. It was introduced in “Control-Flow Bending: On the Effectiveness of Control-Flow Integrity” (Carlini, et al. 2015) and the authors have implemented Brainfuck and an obfuscated tic-tac-toe with it. [0]: https://nebelwelt.net/publications/files/15SEC.pdf https://nebelwelt.net/publications/files/15SEC.pdf [1]: https://github.com/HexHive/printbf https://github.com/HexHive/printbf [2]: https://github.com/carlini/printf-tac-toe https://github.com/carlini/printf-tac-toe
- isatty 3y ago> While its primary purpose is to serve as The One True Debugger, printf also happens to be Turing complete. Excellent.