Hi everybody,

I'm experiencing a weird behaviour when using va_list with gcc 4.1.2
on a x86_64 linux distribution.

Below is my test program (yes, I know about the possible buffer
overflows but please, bear with me, this is just a proof of concept):

#include <stdio.h>
#include <stdarg.h>

int var(const char* fmt, ...)
{
    va_list args;
    char buf[4096];

    va_start(args, fmt);

    vsprintf(buf, fmt, args);
    fprintf(stderr,"\n[%s]", buf);

    vsprintf(buf, fmt, args);
    fprintf(stderr,"\n[%s]", buf);

    va_end(args);

    return 0;
}

int main()
{
    var("Hello world: %s %s %s %d", "hdha", "saooh", "kekek", 34);
    return 0;
}


The problem arising on x86_64 is that the "args" variable gets somehow
modified by the first vsprintf() call, so that when I use it in the
second one, it will point to invalid (?) arguments and fprintf will
print out junk.
What confuses me is that this seems to be 64-bit related, since the
same code, on x86 seems to work! (I'm using gcc 4.2.2 on x86
though...). Also tested this on a 64bit sparc machine and the code
behaves properly, like the one on x86.

Can anyone please explain this behaviour to me? Is it a bug or am I
using va_list in a non-standard way?

Thanks in advance!
#include <stdio.h>
#include <stdarg.h>

int var(const char* fmt, ...)
{
    va_list args;
    char buf[4096];

    va_start(args, fmt);

    vsprintf(buf, fmt, args);
    fprintf(stderr,"\n[%s]", buf);

    vsprintf(buf, fmt, args);
    fprintf(stderr,"\n[%s]", buf);

    va_end(args);

    return 0;
}

int main()
{
    var("Hello world: %s %s %s %d", "hdha", "saooh", "kekek", 34);
    return 0;
}

Reply via email to