How do you call vsnprintf() safely?

后端 未结 3 666
借酒劲吻你
借酒劲吻你 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:23

    This is the correct way to use snprintf and vsnprintf on every operating system except SunOS 4 (which has been obsolete for 20 years), so your problem is somewhere else.

    I'll make a pure guess and say that I'm almost certain that your problem is that you're passing the va_list ap into vsnprintf which consumes it and then you expect it to be reset on the next call. This is incorrect and has stopped working in gcc many years ago (because it only worked on certain architectures).

    Change:

    n = vsnprintf(p, size, fmt, ap);
    

    To:

    va_list apc;
    va_copy(apc, ap);
    n = vsnprintf(p, size, fmt, apc);
    va_end(apc);
    

    And see if that helps.

    Here's a simple test to see what's going on:

    #include 
    #include 
    #include 
    
    void
    foo(const char *fmt, va_list ap)
    {
    #ifdef BAD
        vprintf(fmt, ap);
    #else
        va_list apc;
        va_copy(apc, ap);
        vprintf(fmt, apc);
        va_end(apc);
    #endif
        vprintf(fmt, ap);
    }
    
    void
    bar(const char *fmt, ...)
    {
        va_list ap;
        va_start(ap, fmt);
        foo(fmt, ap);
        va_end(ap);
    }
    
    int
    main(int argc, char **argv)
    {
        bar("foo %s\n", "bar");
        return 0;
    }
    

    When run I get this:

    $ cc -o foo foo.c && ./foo
    foo bar
    foo bar
    $ cc -DBAD -o foo foo.c && ./foo
    foo bar
    foo ����
    

提交回复
热议问题