malloc and buffer overflow attacks

Paul Backus snarwin at gmail.com
Fri Dec 31 13:52:26 UTC 2021


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 if `len*T.sizeof` overflows? malloc() will succeed, but 
> the result will be too small for the data.

For projects using Phobos, an easy way to avoid this is to use 
[`Mallocator`][1] and [`makeArray`][2] from the 
`std.experimental.allocator` package.

     T[] array = Mallocator.instance.makeArray!T(len);

`makeArray` will perform an overflow check internally and return 
`null` if the check fails.

[1]: 
https://dlang.org/library/std/experimental/allocator/mallocator/mallocator.html
[2]: 
https://dlang.org/library/std/experimental/allocator/make_array.html


More information about the Digitalmars-d mailing list