3

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)?

Darth-CodeX
  • 2,166
  • 1
  • 6
  • 23
pelageech
  • 31
  • 4
  • Perhaps it's not what you are asking, but if you want your own printing / logging function, you usually don't handle the arguments yourself, but relay the `args` to one of the [`v*printf`](https://stackoverflow.com/questions/1485805/whats-the-difference-between-the-printf-and-vprintf-function-families-and-when) versions, which take a `va_list` instead of the variadic argument `...`. (And use attributes or SAL comments to get the full `printf`-string diagnostics.) – M Oehm Mar 08 '22 at 06:21
  • An interesting question. – balu Mar 08 '22 at 07:43

1 Answers1

2

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.

rici
  • 234,347
  • 28
  • 237
  • 341