64bit_twitchyliquid
64bit_twitchyliquid

Reputation: 924

Variadic function va_arg() returning incorrect parameters

Problem Partically solved: please read bottom

The variadic function in question, stripped down to the bare simplest is:

inline Variant::Variant(int type, int dims, ...)
{
   va_list ap;
   va_start (ap, dims);

   //Removed Variant handling code here

   int i=0;
   for(;i<dims;i++){
      int size = va_arg (ap, int);
   }


   //Likewise, Removed Variant handling code here

   va_end (ap);
}

As you can see, the function in question is an overloaded constructor for my Variant class. This particular constructor takes in the size and number of dimensions when declaring an array.

So this line runs in my main():

Variant(ARRAY_ARRAYTYPE, 3, 800, 22, 22);

and when I breakpoint right after the

int size = va_arg (ap, int);

line in the function, I get the following results:

size holds the value of 800 (correct)
size holds the value of -43587879... (WTF)
size holds the value of 4387643543 (WTF)

Then the program segfaults because obviously those are completely invalid values.

Any ideas? Thanks in advance.

Problem Partically solved: restart somehow fixed that problem but now a new one ...

My OTHER variadic function, which is called afterwards, seems to pickup whatever parameters were passed to the Variant() constructor rather than its own ones. Any ideas?

Variant* ArAcc(Variant* in_variable, ...)
{
  va_list app;
int index=0;

int i, j;
int mult;

  va_start (app, in_variable->arrayaccess->num_dimensions);
  for(i=0;i<in_variable->arrayaccess->num_dimensions;i++){
    mult = 1;
    for(j=i+1;j<in_variable->arrayaccess->num_dimensions;j++){
        mult = mult * in_variable->arrayaccess->dim_sizes[j];

    }
    int size = va_arg (app, int);
    mult = mult * size;
    index += mult;
  }
  va_end (app);

return &((*in_variable)[index]);
}

with...

ArAcc(&SomeVariant, 7, 9);

Thanks in advance.

Upvotes: 0

Views: 643

Answers (2)

ymett
ymett

Reputation: 2454

Edit: I didn't see that this was already mentioned in a comment.

If a restart solved the problem, that would indicate to me that the problem isn't really solved, just happens not to cause symptoms.

If the first problem really is solved, the following line in the second function may be causing the second problem:

va_start (app, in_variable->arrayaccess->num_dimensions);

That should be

va_start (app, in_variable);

of course.

Based on your comment I suspect that when the first case wasn't working, you were actually passing a local variable as the second parameter to va_start instead of the function argument.

Upvotes: 2

Mayank
Mayank

Reputation: 429

try removing inline and make it a normal function.

Upvotes: 0

Related Questions