Safely extend the size of a malloced memory block after realloc

Walter Bright via Digitalmars-d digitalmars-d at puremagic.com
Mon Aug 17 12:52:53 PDT 2015


On 8/17/2015 12:38 PM, Steven Schveighoffer wrote:
> On 8/17/15 3:27 PM, Benjamin Thaut wrote:
>> void* mem = malloc(500);
>> GC.addRange(mem, 500);
>> mem = realloc(mem, 512); // assume the pointer didn't change
>> GC.removeRange(mem);
>
> This is actually unsafe, you have to remove the range first, or else if it
> *does* change the pointer, your GC is using free'd memory. Plus, if it does
> change the pointer, how do you remove the original range?

Good catch, quite right.


>> // if the GC kicks in here we're f*****
>> GC.addRange(mem, 512);
>
> Can't you GC.disable around this whole thing?

I agree that should work.



More information about the Digitalmars-d mailing list