2

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 ?

7
  • 1
    There is no portable function that could return a pointer to the stack in C. There are only degrees of unportability. Commented Apr 7, 2016 at 9:48
  • This kind of stuff is platform and compiler dependent. Commented Apr 7, 2016 at 9:54
  • The PowerPC ABI does have the notion of stack memory, but your compiler may choose to put variable i in another memory other than the stack. Nevertheless, I'd say it will work with any mainstream PowerPC compiler Commented Apr 7, 2016 at 10:02
  • @atturri: The compiler will have to put the variable i somewhere in memory, if you (correctly) use its address. There's no choice. Commented Apr 7, 2016 at 10:44
  • 1
    @atturri: "the stack" is an informal term anyway, for "the memory area where local variables are stored". By definition, &i points inside the stack. However, there is no guarantee that "the stack" is a contiguous memory area, or that &i is located at either end, or that you can do pointer arithmetic on &i. Commented Apr 7, 2016 at 11:04

1 Answer 1

4

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.

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

1 Comment

Note that the mere act of having a pointer that was once valid isn't UB by itself. This is just the normal state after free(ptr) returns, for instance.

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.