Safely extend the size of a malloced memory block after realloc

Benjamin Thaut via Digitalmars-d digitalmars-d at puremagic.com
Mon Aug 17 22:51:32 PDT 2015


On Monday, 17 August 2015 at 19:38:21 UTC, Steven Schveighoffer 
wrote:
> On 8/17/15 3:27 PM, Benjamin Thaut wrote:
>> Consider the following code
>>
>> 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?

I specifically asked for the case where the pointer doesn't 
change. Obvisouly the case where it does change is easy, you 
first add the new range and then remove the old one. But if you 
do this and the pointer didn't change, the addRange doesn't do 
anything because its a duplicate and the removeRange then removes 
the range, because the pointer is still the same. You then end up 
with the GC not knowing anything about the range anymore.

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

Yes, this would work, but It seems kind of broken to me, that you 
have to make 4 API Calls to the gc to handle something as simple 
as a realloc.

Kind Regards
Benjamin Thaut




More information about the Digitalmars-d mailing list