alloca(0) 在不同平台上做什么并返回什么?
如果给定的大小为 0,alloca()
是否返回 NULL?
快速搜索发现,alloca(0)
在某些情况下会强制进行垃圾回收!但我最感兴趣的是返回值。
谢谢
Does alloca()
returns NULL if the size given is 0?
A quick search reveals that alloca(0)
force garbage collection in some cases! but I am mostly interested by return value.
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
alloca 的 gcc-2.95 实现使用 malloc 本身从堆中分配内存。在该实现的上下文中,alloca (0) 相当于:
free(/*当堆栈指针较深时使用 alloca 分配的所有内存*/)
。这里引用了 gcc-2.95 的 alloca.c 文件中的注释。
顺便说一句,在此实现中 alloca(0) 返回 NULL。
The gcc-2.95 implementation of alloca allocates memory from the heap using malloc itself. In the context of that implementation alloca (0) is equivalent to:
free (/*all the memory that was allocated with alloca when the stack pointer was deaper*/)
.Here's a quotation from a commentary in the alloca.c file of the gcc-2.95.
By the way in this implementation alloca(0) returns NULL.
根据 this manpage,
alloca
将在堆栈上分配内存,它要么成功,要么让你的程序崩溃。现在,对于 0 字节的分配,您不必担心返回值:因为有 0 字节,所以没有空间可供您写入,并且无论返回的指针值是否为
0x1234
或 NULL,程序无论如何都会崩溃。According to this manpage,
alloca
will allocate memory on the stack, and it will either succeed, or make your program crash.Now, for an allocation of 0 bytes, you should not bother about the returned value: since there are 0 byte, there is no space for you to write, and no matter if the pointer value returned is
0x1234
or NULL, the program should crash anyway.在 Windows 上,
_alloca(0);
返回堆栈指针(具有一些固定偏移量。)在某些特殊情况下,当 C 代码需要从某个寄存器中了解RSP
CPU 寄存器时,这可能是必要的。x64
进程(因为 Visual Studio 中的 64 位版本不支持内联汇编。)但请记住,调用
_alloca(0);
将在堆栈,因此请确保不要在同一本地范围内重复调用它,否则可能会耗尽堆栈并导致堆栈溢出异常。作为更好的选择,请考虑调用
_AddressOfReturnAddress()
内在的。On Windows,
_alloca(0);
returns the stack pointer (with some fixed offset.) This may be necessary in some exceptional situations when C code needs to know theRSP
CPU register from within anx64
process (since inline assembly is not supported for 64-bit builds in Visual Studio.)Keep in mind though, that calling
_alloca(0);
will allocate some memory on the stack, so make sure not to call it repeatedly in the same local scope, as otherwise that may deplete your stack and cause thestack overflow
exception.As a much better alternative, consider calling
_AddressOfReturnAddress()
intrinsic instead.根据 Linux 手册页
所以 alloca()ing 0 大小的元素是不合法的,但没有定义
我没有 size=0 时返回值的具体示例。请看一下这个问题和第一个链接的“GNU 版本注释”
According to Linux man pages
So alloca()ing 0 size elements is not legal but not defined
I don't have a specifical example of the return value when size=0. Please, take a look at this question and "Notes on the GNU Version" at the first link