How do you call vsnprintf() safely?

后端 未结 3 675
借酒劲吻你
借酒劲吻你 2021-01-14 02:06

I\'m porting some very old (> 10y) C code to modern Linuxes. I\'m getting segmentation faults within a custom-written vsnprintf() wrapper (apparently its task is to detect d

3条回答
  •  感动是毒
    2021-01-14 02:43

    As I understand the code, its purpose is to detect the size needed by sprintf to fully write the output string in the buffer. There is a function that do this for you: asprintf (or vasprintf here).

    Prototype:

    int vasprintf(char **strp, const char *fmt, va_list ap);
    

    Just use it as follow:

    String strVPrintf(const String fmt, va_list ap)
    {
        char *ans;
        int n;
        n = vasprintf(&ans, fmt, ap);
        // do the checks
        return ans;
    }
    

    With this function, you do not need this wrapper any more, I think.

提交回复
热议问题