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

拜拜、爱过 提交于 2019-12-11 13:04:07

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/36472344/how-to-write-a-function-which-return-a-pointer-to-the-stack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!