Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

5
  • Do you realize that the above code snippet is vulnerable to buffer overruns? sprintf doesn't check the size of the buffer! Commented Aug 20, 2021 at 3:19
  • 1
    @Sapphire_Brick It really isn't. The length of the format string will be 7 + the number of digits in the base 10 representation of the length of name. If that length is greater than 24, you will have other issues. If you want to be safe and use snprintf you certainly could, but this will work for buffers that are significantly larger than a petabyte. Commented Aug 20, 2021 at 3:36
  • In order to overflow the buffer, you would need to be creating an automatic array that is about 8 yotta-bytes, since you won't overflow the buffer until Name is over 2^83 bytes in size. In practical terms, this is not a problem. But, yes, snprintf should always be preferred over sprintf. Code edited. Commented Aug 20, 2021 at 11:56
  • Is there any advantage of using scanf in this fashion rather than simply using a getchar() loop? Commented Nov 24, 2022 at 21:16
  • @supercat Absolutely not. IMO, scanf should never be used for anything, but it seems to be a popular choice and is regularly abused. Commented Nov 25, 2022 at 16:06