Safely extend the size of a malloced memory block after realloc

Benjamin Thaut via Digitalmars-d digitalmars-d at puremagic.com
Mon Aug 17 12:27:09 PDT 2015


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);
// if the GC kicks in here we're f*****
GC.addRange(mem, 512);



I digged into GC.addRange to find out if I simply can skip the 
call to GC.removeRange when the pointer doesn't change and ended 
up with

void addRange(void *pbot, void *ptop, const TypeInfo ti) nothrow 
@nogc
{
     ranges.insert(Range(pbot, ptop));
}

where ranges is defined as: Treap!Range ranges

"insert" of Treap is implemented as:

Node* insert(Node* node, E element) @nogc
{
     if (!node)
         return allocNode(element);
     else if (element < node.element)
     {
         node.left = insert(node.left, element);
         if (node.left.priority < node.priority)
             node = rotateR(node);
     }
     else if (element > node.element)
     {
         node.right = insert(node.right, element);
         if (node.right.priority < node.priority)
             node = rotateL(node);
     }
     else
     {} // ignore duplicate

     return node;
}

The problem is the line that says "ignore duplicate". Because 
that way I can not safly update a GC range.

How are you supposed to safely update a GC range that changed its 
size but not its address? The documentation doesn't say anything 
about it.

Either I'm missing something or this is a bug.

Kind Regards
Benjamin Thaut


More information about the Digitalmars-d mailing list