Skip to content

Is the lock released too early during reference count decrement? #4

@S-Maple

Description

@S-Maple

Hi ,
I've been reading through your code and have a question about the reference counting implementation:
`void ref_release(void *ptr)
{
obj_t *obj;
char *cptr;
int dofree = 0;

cptr = (char *)ptr;
cptr -= sizeof(obj_t);
obj = (obj_t *)cptr;

pthread_mutex_lock(&obj->mutex);
if (--obj->ref == 0) {
dofree = 1;
}
pthread_mutex_unlock(&obj->mutex);
if (dofree) {
pthread_mutex_destroy(&obj->mutex);
free(obj);
}
}`
The current implementation releases the lock immediately after decrementing the reference count. Could this lead to a race condition?

Scenario I'm worried about:
Thread A calls ref_release(), decrements the count to 0, sets dofree = 1, then releases the lock.Before Thread A does free(), Thread B calls ref_retain().Thread B successfully acquires the lock, increments the reference count, and returns.Thread A then proceeds to destroy the mutex and free the memory.Thread B now holds a dangling pointer to freed memory
Would it be safer to hold the lock until after the destruction/free operations are complete? Or is there another synchronization mechanism ensuring this can't happen?
Thanks for your time!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions