malloc and buffer overflow attacks

Adam Ruppe destructionator at
Fri Dec 31 00:15:48 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 I do in D is always slice the malloc to the given size 

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.

More information about the Digitalmars-d mailing list