C (programming language): Difference between revisions

no edit summary
No edit summary
Line 11: Line 11:
Memory allocated by <code>alloca</code> is allocated on the stack and will automatically be freed. Do not call <code>free</code> on this memory. Do not allocate more than a few bytes using <code>alloca</code> or you will risk a stack overflow leading to undefined behavior.<br>
Memory allocated by <code>alloca</code> is allocated on the stack and will automatically be freed. Do not call <code>free</code> on this memory. Do not allocate more than a few bytes using <code>alloca</code> or you will risk a stack overflow leading to undefined behavior.<br>
For automatic garbage collection, use [[C++]] which has smart pointers.
For automatic garbage collection, use [[C++]] which has smart pointers.
{{ hidden | <code>_malloca</code> |
On Windows you also have:
* <code>_malloca</code>
* <code>_calloca</code>
These are not portable so I wouldn't use them. They are a safer version of <code>alloca</code> which allocates to the heap if there isn't enough stack space. However, you need to free them using <code>_freea</code> which eliminates the main benefit of <code>alloca</code>.<br>
As far as I can tell, the only benefit is to prevent heap fragmentation.
}}