问题描述
有没有办法在(而不是堆)上分配内存?
Is there a way to allocate memory on stack instead of heap? I can't find a good book on this, anyone here got an idea?
推荐答案
使用(有时称为 _alloca()
或),但—它会释放它的内存,当你离开一个函数,而不是当你超出范围,所以如果你使用它在一个循环内,你会很快爆炸。
Use alloca()
(sometimes called _alloca()
or _malloca()
), but be very careful about it — it frees its memory when you leave a function, not when you go out of scope, so you'll quickly blow up if you use it inside a loop.
,如果你有一个函数像
For example, if you have a function like
int foo( int nDataSize, int iterations )
{
for ( int i = 0; i < iterations ; ++i )
{
char *bytes = alloca( nDataSize );
// the memory above IS NOT FREED when we pass the brace below!
}
return 0;
} // alloca() memory only gets freed here
分配额外的 nDataSize字节。没有alloca()字节获得释放,直到你从函数返回。因此,如果你有一个 nDataSize
1024和一个迭代
8,你将在返回前分配8千字节。如果你有一个 nDataSize
= 65536和 iterations
= 32768,你将分配一个总共65536× 32768 = 2,147,483,648字节
Then the alloca() will allocate an additional nDataSize bytes every time through the loop. None of the alloca() bytes get freed until you return from the function. So, if you have an nDataSize
of 1024 and an iterations
of 8, you'll allocate 8 kilobytes before returning. If you have an nDataSize
= 65536 and iterations
= 32768, you'll allocate a total 65536×32768=2,147,483,648 bytes, almost certainly blowing your stack and causing a crash.
anecdote:如果你写入超过缓冲区的末尾,你很容易陷入麻烦,特别是如果你将缓冲区传递到另一个函数,那个子函数对缓冲区的长度有错误的想法。 ,我们使用 alloca()
创建临时存储,用于在将TrueType字体glyph发送到GPU内存之前呈现TrueType字体glyph。我们的字体库没有说明瑞典语Å中的变音符号;字符,因此它告诉我们在渲染之前分配 n 字节来存储字形,然后实际渲染 n +128字节。额外的128个字节写入调用栈,覆盖返回地址并引发一个非常痛苦的非确定性崩溃!
anecdote: You can easily get into trouble if you write past the end of the buffer, especially if you pass the buffer into another function, and that subfunction has the wrong idea about the buffer's length. I once fixed a rather amusing bug where we were using alloca()
to create temporary storage for rendering a TrueType font glyph before sending it over to GPU memory. Our font library didn't account for the diacritic in the Swedish Å character when calculating glyph sizes, so it told us to allocate n bytes to store the glyph before rendering, and then actually rendered n+128 bytes. The extra 128 bytes wrote into the call stack, overwriting the return address and inducing a really painful nondeterministic crash!
这篇关于C ++如何在堆栈上动态分配内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!