Rockybilly
Rockybilly

Reputation: 4510

C basic memory management implementation

I am trying to write a basic memory management system to a C library project in a GCC environment, and came here to ask if what I am doing is permitted or advisable by C standards.

Basically, my code base is huge, and contains many required and non-required malloc operations inside the code. It's not that I am so careless to put malloc everywhere I wanted, but I didn't have the information about which values were necessary until the nearing end of the project.

Basically my plan is to create a global reference counter that is shared between translation units. And write a malloc wrapper that increments and adds to this reference count, and store the pointers inside. So what remains is to free all the references in a loop at the end of the run time. I activate this at the very end of the run time, so reference lifetime is not a issue for me to track, therefore somewhat makes the problem easier.

I also need to ask this important question. I have many types of pointers in the code. So when reference counting, I have to store these as void*, will this cause undefined behavior and create an issue ?

Edit: These values that I refer to being stored as void* are regular pointers that allocated with malloc (could be char*, int*, struct* etc...), and used inside the code. However given that the reference counter will not know the types of these, so I plan to keep them in a list of void*.

As to the OS clean-up suggestion, unfortunately, I am creating a large library base rather than an executable, so even though my code ends running, I should free the memory so the library user won't have problems (the user's code does not end after it calls my library functions, that why I cannot depend on OS clean-up)

Edit2: Let's create a small example of what I am planning to do.

int ref_count = 0;
void* ref_list[64]; // 64 is arbitrary.

void* mallocWrapper(size_t size){
    void* result = malloc(size);
    ref_list[ref_count] = result;
    ref_count += 1;
    return result;
}

Then use this list to free all the allocated memory in the code.

Upvotes: 0

Views: 132

Answers (1)

Prof. Falken
Prof. Falken

Reputation: 24887

Yes, that's a valid way to do it. malloc() returns just a pointer, it doesn't know about types at all, just chunks of memory.

Note, if you free() stuff in your library, you will have to write a freeWrapper() too, or you will end up freeing some things twice.

Upvotes: 1

Related Questions