Replacing malloc with alloca.
Florian Weimer
fw@deneb.enyo.de
Sun Sep 13 19:43:00 GMT 2015
* Jeff Law:
> On 09/13/2015 12:28 PM, Florian Weimer wrote:
>> * Ajit Kumar Agarwal:
>>
>>> The replacement of malloc with alloca can be done on the following
>>> analysis.
>>>
>>> If the lifetime of an object does not stretch beyond the immediate
>>> scope. In such cases the malloc can be replaced with alloca. This
>>> increases the performance to a great extent.
>>
>> You also need to make sure that the object is small (less than a page)
>> and that there is no deep recursion going on. Otherwise, the program
>> may no longer work after the transformation with real-world restricted
>> stack sizes. It may even end up with additional security issues.
> You also have to make sure you're not inside a loop. Even a small
> allocation inside a loop is problematical from a security standpoint.
>
> You also need to look at what other objects might be on the stack and
> you have to look at the functional scope, not the immediate scope as
> alloca space isn't returned until the end of a function.
Ah, right, alloca is unscoped (except when there are variable-length
arrays).
Using a VLA might be the better approach (but the size concerns
remain). Introducing VLAs could alter program behavior in case a
pre-existing alloca call, leading to premature deallocation.
More information about the Gcc
mailing list