如何写一个返回指针到堆栈功能 [英] How to write a function which return a pointer to the stack

查看:211
本文介绍了如何写一个返回指针到堆栈功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看完下面的<一个href=\"http://stackoverflow.com/questions/28358213/portable-function-in-c-with-no-assembly-that-returns-the-size-of-its-stack-fra\">question,据我所知,有没有这样的事情存在(至少不是便携)。

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

不过,我主演在以下的从单声道code基地,返回一个指针到堆栈件code 的:

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;
}

我很惊讶的是,上述code甚至可以在足弓工作,如PowerPC的,我都会以为这只会在x86(也许只有GCC)。

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).

这种的PowerPC上工作?

Is this going to work on PowerPC ?

推荐答案

堆栈的目的是支持函数调用和局部变量。如果你的系统有一个栈,它会使用它,并分配局部变量存在。所以这是非常合理的假设,局部变量的点某处堆栈中的地址。这不是专门针对x86或GCC - 这是一个相当普遍的想法。

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.

但是,使用指针变量不存在(即,它超出范围后)是未定义的行为。所以这个功能不能保证做任何有意义。事实上,一个聪明的编译器可以检测到你的程序使用未定义的行为,并通过无操作取代你的code(并称之为性能优化)。

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.

选项也不保证 - 这code是不可移植

Neither option is guaranteed - this code is not portable.

这篇关于如何写一个返回指针到堆栈功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆