malloc and buffer overflow attacks
sarn
sarn at theartofmachinery.com
Fri Dec 31 00:37:20 UTC 2021
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.
More information about the Digitalmars-d
mailing list