Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vsnprintf and varargs not working, weird results

I'm using vsnprintf (as far as I know correctly) but am getting weird results. I've simplified my code down to the following example:

void func(char *aaa, ...)
{
    char *buf;
    va_list args;
    int size;

    va_start(args, aaa);
    size = vsnprintf(NULL, 0, aaa, args)+1;
    buf = malloc(size);
    vsnprintf(buf, size, aaa, args);
    printf("%s",buf);
    free(buf);
    va_end(args);
}

int main(int argc, char **argv)
{
    func("abc %s", "def\n");
    return 0;
}

I'd expect "abc def" to get printed, but instead I get "abc" followed by some garbage text. Does anyone have an idea of where I messed up?

like image 793
John Avatar asked Feb 12 '23 14:02

John


1 Answers

va_start(args, aaa);
size = vsnprintf(NULL, 0, aaa, args)+1; // Reads all arguments
buf = malloc(size);
vsnprintf(buf, size, aaa, args); // Tries to read all arguments again
printf("%s",buf);
free(buf);
va_end(args);

See the commented lines. You have to reset args between those two calls consuming all arguments.

Insert:

va_end(args);
va_start(args, aaa);
like image 183
Deduplicator Avatar answered Feb 16 '23 04:02

Deduplicator