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?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
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
nDataSizeof 1024 and aniterationsof 8, you’ll allocate 8 kilobytes before returning. If you have annDataSize= 65536 anditerations= 32768, you’ll allocate a total 65536×32768=2,147,483,648 bytes, almost certainly blowing your stack and causing a crash.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!