1

There is a function my_init(...) that uses a variable argument list. The length of this list is not known, but there is a maximum of 100 and the elements are always char-arrays (means plain C-strings).

That's how I try to decode them:

void my_init(...)
{
    va_list vl; 
    int     tagCnt,tagLen=100; 
    char   *listTag,*listValue;

    va_start(vl,tagLen);
    for (tagCnt=0; tagCnt<50; tagCnt++)
    {
        listTag=va_arg(vl,char*);
        if (listTag==0) break;
        listValue=va_arg(vl,char*);

        ... // do some usefult things here
    }
    va_end(vl);
}

...and I call this function this way:

my_init("tag1","value1",
        "tag2","value2",
        0);

So there are always pairs and the end of a list is marked with a 0. Unfortunately my_init() fails, after calling va_start() vl contains some crap that has nothing to do with input parameters and the calls to va_arg() return invalid pointers. So what is wrong in my code?

The code given above is shortened a bit so may be it does not compile...

Thanks!

==================================================================================

EDIT:

I changed code and call this way:

void my_init(int dummy,...)
{
    va_list vl; 
    int     tagCnt,tagLen=100; 
    char   *listTag,*listValue;

    va_start(vl,dummy);
    for (tagCnt=0; tagCnt<50; tagCnt++)
    {
        listTag=va_arg(vl,char*);
        if (listTag==0) break;
        listValue=va_arg(vl,char*);

        ... // do some usefult things here
    }
    va_end(vl);
}

my_init(0,
        "tag1","value1",
        "tag2","value2",
        0);

Independent from the used header file I now get other crap in my vl, stdargs.h or varargs.h do not make a difference...

5
  • What header file do you include to define va_* macros? Is it stdarg.h? Probably varargs.h can help? Commented Feb 4, 2013 at 14:18
  • Did you try to compile without optimization? Commented Feb 4, 2013 at 14:32
  • Yes, its a Debug-Build without any optimisations - but that should not have an influence, the release build should work too!? Commented Feb 4, 2013 at 14:33
  • Can you produce a minimal test-case? Commented Feb 4, 2013 at 15:51
  • OK, solved - I used an intermediate step where arglist was handed over to an other function - and this was done in a wrong way. Commented Feb 5, 2013 at 6:44

1 Answer 1

1

The second argument to va_start must be the last named function parameter. In other words, the canonical usage is this:

void my_func(int arg1, float arg2, ...) {

    va_list vl;

    va_start(vl, arg2);

    // Stuff
}
Sign up to request clarification or add additional context in comments.

2 Comments

There is no functional parameter, only the variable list is accepted. So isn't there a way to implement it without?
@Elmi: Exactly. You need at least one named parameter.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.