Search code examples
cmemory-managementmemory-leaksmallocrealloc

Resizing Heap Memory


So I am trying to make a very simple wrapper around malloc() and realloc() for a lazy solution to a garbage collector. Problem is designing the garbage collector buffer. I want to store a pointer to pointers.

So I would need to initially allocate so arbitrary size of memory at initialisation. The problem is within this function I think. I want this function to be able to resize the buffer if it detected that the buffer is full. But currently, it is only happy if I either have a big buffer so I would not need to use this function.

typedef struct ALLOC_STRUCT {
    void *cur_ptr;
    int index;
} alloc_T;

typedef struct GC_STRUCT {
    alloc_T **buffer; // Pointer that points to array of alloc_T pointers.
    int count; // Size of the buffer.
} gc_T;

void gc_resize(gc_T *gc) {
    if (gc->count == 4 && gc->count != 0) {
        gc_T *new_gc = realloc(gc, (sizeof *new_gc) + sizeof(uintptr_t) * (gc->count + ALLOCATION));
        if (new_gc) {
            gc = new_gc;
            gc->buffer = realloc(gc->buffer, sizeof(uintptr_t) * (gc->count + ALLOCATION));
            gc->count = gc->count;
        } else {
            // Error handling
        }
    }
}

I was wondering if this problem could be either too much realloc() calls (which I do not think that to be the case) or my implementation of the garbage collector is wrong. Can anyone find any problems?

Here is the source code if anyone is really interested: https://github.com/Zernoxi/New_Programming_Language/tree/memory_experiment/src


Solution

  • Thanks to @JoëlHecht and @4386427 for the help. It seems that I have misinterpreted with how double pointers work.

    void gc_resize(gc_T *gc) {
        if (gc->count % 13 == 0 && gc->count != 0) {
            new_buffer = realloc(gc->buffer, sizeof(void *) * (gc->collect + 14));
            if (new_buffer == NULL) {
                // Error handling
            }
            gc->buffer = new_buffer;
        }
    }