为什么 C 从来没有实现“堆栈扩展"? [英] Why did C never implement "stack extension"?

查看:26
本文介绍了为什么 C 从来没有实现“堆栈扩展"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 C 从未实现堆栈扩展"以允许调用者引用被调用函数的(动态大小的)堆栈变量?

Why did C never implement "stack extension" to allow (dynamically-sized) stack variables of a callee function to be referenced from the caller?

这可以通过扩展调用者的堆栈帧来包括来自被调用者的堆栈帧的动态返回"变量来实现.(您可以,但不应该,使用来自调用方的 alloca 实现此功能 - 它可能无法通过优化.)

This could work by extending the caller's stack frame to include the "dynamically-returned" variables from the callee's stack frame. (You could, but shouldn't, implement this with alloca from the caller - it may not survive optimisation.)

例如如果我想返回动态大小的字符串e",实现可能是:

e.g. If I wanted to return the dynamically-size string "e", the implementation could be:

--+---+-----+
  | a |  b  |
--+---+-----+

callee(d);

--+---+-----+---------+---+
  | a |  b  |  junk   | d |    
--+---+-----+---------+---+

char e[calculated_size];

--+---+-----+---------+---+---------+
  | a |  b  |  junk   | d |    e    |    
--+---+-----+---------+---+---------+

dynamic_return e;

--+---+-----+-------------+---------+
  | a |  b  |    waste    |    e    |
--+---+-----+-------------+---------+

(垃圾"包含程序不可见的返回地址和其他特定于系统的元数据.)

("Junk" contains the return address and other system-specific metadata which is invisible to the program.)

使用时会浪费一点堆栈空间.

This would waste a little stack space, when used.

好处是字符串处理的简化,以及任何其他当前必须malloc ram、返回指针并希望调用者记得在free合适的时间.

The up-side is a simplification of string processing, and any other functions which have to currently malloc ram, return pointers and hope that the caller remembers to free at the right time.

显然,在 C 的生命周期的这个阶段向 C 添加这样的功能没有意义,我只是想知道为什么这不是一个好主意.

Obviously, there is no point in added such a feature to C at this stage of its life, I'm just interested in why this wasn't a good idea.

推荐答案

一个新的对象可能会通过多层软件返回.所以浪费的空间可能来自几十个甚至上百个函数调用.

A new object may be returned through many layers of software. So the wasted space may be that from dozens or even hundreds of function calls.

还要考虑一个执行一些迭代任务的例程.在每次迭代中,它从子程序中获取一些新分配的对象,并将其插入到链表或其他数据结构中.这种迭代任务可能会重复数百、数千或数百万次迭代.堆栈将溢出,浪费空间.

Consider also a routine that performs some iterative task. In each iteration, it gets some newly allocated object from a subroutine, which it inserts into a linked list or other data structure. Such iterative tasks may repeat for hundreds, thousands, or millions of iterations. The stack will overflow with wasted space.

这篇关于为什么 C 从来没有实现“堆栈扩展"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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