pelageech
pelageech

Reputation: 31

How can I count the number of bytes passed to a va_list function using format

For an example, I have a function foo()

int foo(const char* format,...) {
   va_list args;
   va_start(args, format)
   ...
   va_end(args);
   return bytes;
}

I have a format "%d%lf%s" and some arguments int a, double b and char* c is null-terminated string. How to pull variables from args and calculate sizeof(a)+sizeof(b)+sizeof(c)?

Upvotes: 3

Views: 141

Answers (1)

rici
rici

Reputation: 241881

You cannot tell how many bytes were passed in the call, whatever that might mean. (Some arguments can be passed in registers. Some arguments might have padding between them.)

You can compute the sum of the sizeof the expected arguments, but it's tedious. You need to parse the format string; every time you find a format specifier, you add the size of the expected corresponding argument. Make sure you take length modifiers into account; %llu corresponds to sizeof(long long int), for example. However, %hu corresponds to an unsigned short which has been converted to an unsigned int; whether you want to count that as sizeof(short) or sizeof(int) might depend on what you plan to do with the answer.

Upvotes: 2

Related Questions