Search code examples
cx86powerpcstack-frame

How to write a function which return a pointer to the stack


After reading the following question, I understand that there no such thing exist (at least not 'portable').

However I am starring at the following piece of code from mono code base, which return a pointer to the stack:

static void *
return_stack_ptr ()
{
    gpointer i;
    return &i;
}

I am surprised that the above code can even work on arch such as PowerPC, I would have assumed this would only work on x86 (and maybe only gcc).

Is this going to work on PowerPC ?


Solution

  • The purpose of the stack is supporting function calls and local variables. If your system has a stack, it's going to use it, and allocate the local variable there. So it's very reasonable to assume that the address of the local variable points somewhere in the stack. This is not specific to x86 or gcc - it's a fairly general idea.

    However, using a pointer to a variable that doesn't exist (i.e. after it goes out of scope) is Undefined Behavior. So this function cannot be guaranteed to do anything meaningful. In fact, a "clever" compiler could detect that your program uses undefined behavior, and replace your code by a no-op (and call it a "performance optimization").

    Alternatively, a "wise" compiler could recognize that your function returns a pointer to the stack, and inline it by using a hardware stack pointer instead.

    Neither option is guaranteed - this code is not portable.