S
S
sttie2020-02-04 16:21:37
C++ / C#
sttie, 2020-02-04 16:21:37

How are the arguments of a function with a variable number of parameters arranged in memory?

I am writing an OS (important, it will not work to use stdarg), there was a need for a function with a variable number of parameters. Such a function (summing n numbers):

int test(int n, ...)
{
  int result = 0;

  for (int* ptr = &n; n > 0; n--)
  {
    ptr++;
    result += *ptr;
  }

  return result;
}


works. And if you call such a function (with arguments "test", 'q'):

void test(char* format, ...)
{
    char* ptr = format;

    for (int i = -10; i < 10; i++)
    {
        putc(*(ptr+i));
    }
}


then the function will output: 5e396f7a8be4e262436588.png
Expectations were such that at least somewhere the letter q should have appeared, which did not happen. Where is she then?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2020-02-04
@jcmvbkbc

I am writing the OS (important, it will not work to use stdarg)

Stop here and read about __builtin_va_list, __builtin_va_start, __builtin_va_arg and __builtin_va_end.
Because the compiler knows the ABIs of variadic functions, it also knows how to handle them.
And if you call such a function (with arguments "test", 'q'):
void test(char* format, ...)
{
    char* ptr = format;

    for (int i = -10; i < 10; i++)
    {
        putc(*(ptr+i));
    }
}

The expectations were such that at least somewhere the letter q should have appeared, which did not happen.

You were just looking in the wrong place: instead of moving along the stack, you moved around the memory around the first parameter.
This is how I would find it...
void test(char* format, ...)
{
    char *ptr = (char *)&format;

    for (int i = -10; i < 10; i++)
    {
        putc(*(ptr+i));
    }
}

...if the arguments really were always on the stack. But this is not always the case - it all depends on the ABI used.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question