How to improve buffer size determination for printfing various integer types?

后端 未结 4 1118
萌比男神i
萌比男神i 2021-01-21 09:36

When converting an integer to text, typically I create a big buffer to use with sprintf() to hold any potential result.

char BigBuffer[50];         


        
4条回答
  •  醉话见心
    2021-01-21 10:12

    These are fine.

    I designed the original snprintf() function (in *BSD, that eventually made it into C99) to return the number of characters that would have been printed, had the buffer been large enough. If you have a conforming snprintf() you can do the printing twice, with the first telling you how much space to allocate (you must add one for the terminating '\0' of course). This has two obvious drawbacks: it has to do the formatting twice, and it introduces the possibility of synchronization issues, where the first call changes something (e.g., writing via %n directive) so that the second call produces different output.

    Unfortunately, there are non-compliant snprintf() implementations where this does not work anyway. [Edit: it works for the usage in jxh's answer, where you supply a large buffer; the failing case is when you supply a too-small buffer to find out how much room you need.]

提交回复
热议问题