raspberrypi / pico-sdk

BSD 3-Clause "New" or "Revised" License
3.24k stars 837 forks source link

Variadic function breaks print format argument #1740

Closed Slion closed 1 week ago

Slion commented 1 week ago

Pico W SDK 1.5.1

Can't get simple variadic function to work for some reason. printf works fine but my own variadic function breaks arguments formatting somehow.

#include <stdarg.h>

int log_debug(const char *fmt,...) {
    int     n;
    va_list args;
    va_start (args, fmt);
    n = printf(fmt, &args);
    va_end(args);
    return n;
}

int main() {    
…
    printf("Printf work fine - One: %d - Two: %d - Three: %d - Four: %d\n", 1, 2, 3, 4);
    log_debug("Broken variadic - One: %d - Two: %d - Three: %d - Four: %d\n", 1, 2, 3, 4);
…
}

That's the output I get:

Printf work fine - One: 1 - Two: 2 - Three: 3 - Four: 4
Broken variadic - One: 537141204 - Two: 2 - Three: 537141220 - Four: 268467736
rhulme commented 1 week ago

You should call vprintf in your variadic function, not printf (and just pass args rather than &args. Otherwise you've told printf to display four integers but only passed one argument (the address of a va_list variable). See https://en.cppreference.com/w/c/io/vfprintf.

Slion commented 1 week ago

Thanks, that did it! My C is a little bit rusty 😁

int log_debug(const char *fmt,...) {
    int     n;
    va_list args;
    va_start (args, fmt);
    n = vprintf(fmt, args);
    va_end(args);
    return n;
}