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

后端 未结 4 1116
萌比男神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:25

    Here's a scheme, expanding my earlier comment. You use the INTMAX_DECIMAL_BUFN as your worst case buffer size, and use it for printing with snprintf(). The value returned by snprintf() is used to declare a VLA that matches exactly the array size needed for the printed string, and that string is copied to the VLA.

    #define INTMAX_DECIMAL_BUFN ((size_t) (sizeof(intmax_t)*CHAR_BIT*0.302) + 3)
    
    char numstr[INTMAX_DECIMAL_BUFN];
    
    int main () {
        int n = snprintf(numstr, sizeof(numstr), "%hu", USHRT_MAX);
        char usbuffer[n+1];
        strcpy(usbuffer, numstr);
        printf("Size:%zu Len:%zu %s\n", sizeof(usbuffer), strlen(usbuffer), usbuffer);
    }
    

    If thread safety is an issue, the numstr variable could be made thread local (with C.11's _Thread_local, or some compiler specific extension similar to GCC's __thread).

    The value of this solution depends on whether the savings in stack space is worth the extra compute to perform the strcpy(). If most of your numbers using the larger integer types actually take on values much smaller than the max, then this technique could provide you with significant savings (depending on how many arrays you are creating).

提交回复
热议问题