'Is it safe to use printf("%*s", len, ptr) where len is an integer and ptr is non-null terminated?
Is it safe to use printf("%*s", len, ptr) where len is an integer and ptr is non-null terminated? If not safe, what will happen in the worst case? And then how can I make it safe?
thank you
Solution 1:[1]
No not safe at all. "%*s" only sets a minimum display width, it does not enforce input string length at all.
But assuming you actually mean "%.*s"
Yes, that would be safe.
This format of printf does not look at chars in/at ptr past the nth (index n-1)
So assuming that n holds an appropriate value there will be no access outside of the allocation unit of ptr and thus no risk of out-of-range pointer undefined behaviour.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
