malloc and buffer overflow attacks

rikki cattermole rikki at cattermole.co.nz
Fri Dec 31 01:12:16 UTC 2021


On 31/12/2021 1:37 PM, sarn wrote:
> On Friday, 31 December 2021 at 00:15:48 UTC, Adam Ruppe wrote:
>> On Friday, 31 December 2021 at 00:13:56 UTC, Walter Bright wrote:
>>> While D offers buffer overflow detection, it does not protect against 
>>> buffer overflows resulting from an array size calculation overflow:
>>>
>>>     T* p = cast(T*)malloc(len * T.sizeof);
>>
>> What I do in D is always slice the malloc to the given size immediately;
>>
>> T[] p = (cast(T*)malloc(len * T.sizeof))[0 .. len * T.sizepf];
>>
>> Then you'd get the protection of bounds checking and if you need the 
>> ptr, there's still that property.
>>
>> I'd suggest everyone always do that.
> 
> Good thing to do, but Walter's talking about integer overflow with the 
> `len * T.sizeof` calculation itself.
> 
> calloc() doesn't have this problem.

I would argue any usage of malloc and even calloc is itself a bug in 
your code.

Ideally we would deprecate malloc and calloc from being called directly 
and force people to use a callocSlice version of it instead.

This solves most of these issues out right and allows for D's memory 
safety features to come into play.


More information about the Digitalmars-d mailing list