3

When function arguments are of the same type, is following code well-defined and portable?

void foo(int* p, int size);
void pass_on_args_by_pointer(int a, int b, int c)
{
    foo(&a, 3);
}

To clearify: the 'size' argument should contain the number of elements in the array p. So, I want to pass all three ints to foo.

3
  • 6
    Are you expecting foo to be able to access b and c somehow? If so, no. Commented Aug 14, 2013 at 10:45
  • That is indeed the question. I realise could've stated it clearer, but the size argument is meant to pass the number of elements in the array p. Commented Aug 14, 2013 at 10:55
  • And what if parameters get passed in registers? Commented Aug 14, 2013 at 11:04

3 Answers 3

7

No, this is neither portable nor well-defined. Compilers are not required to allocate function parameters in adjacent locations in memory. In fact, they are not required to place parameters b and c in memory at all, since you are not taking their address. Any access beyond the bounds of the int through p in foo is undefined behavior.

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

Comments

0
void foo(int** p, int size)
{
   **p = size;
    return;
}
void pass_on_args_by_pointer(int *a, int b, int c)
{
   foo(&a, 3);
}

int main(void)
{
    int a = 0;
    pass_on_args_by_pointer(&a, 0, 0);
    printf("a = %d", a);

}

If you want to assign some value to varaiable a, you need to use pointer to pointer.

Comments

-1

Even if it would possibly work (In theory, it should, because the stack can be represented as an array), your compiler is not obligated to to pass the arguments on the stack. It could for example use registers instead to optimise your code, and then your code will break.

So trying to access another function's arguments this way would be undefined behavior.

2 Comments

Incorrect assumption. The stack cannot be represented as an array, as far as the C++ standard is concerned.
I do not talk about any particular language's standard's concerns, I talk about the CPU's stack in memory. E.g 3 32bit integers on the stack can be represented as an 3-element sized array (an array again, in no particular language)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.