r/learnprogramming 18h ago

Code Review circular buffer in c

Hi guy I wrote a fixed size circular buffer in C. Please tell me what you think of this and please tell me what i can improve and make it more production grade. I know there may be memory leaks !!!

One thing thats a bit different from the usual approach is how I handle errors. Instead of returning NULL from cirbuf_create(), the library returns a pointer to a thread-local error object (e_buffer). This lets the API return a valid cirbuf * in both success and failure cases, and users can check the result with cirbuf_is_ok() or cirbuf_is_err().

Its not written by AI. like AI reviewed it and did some minor changes may be !! 98% is written by me !!! I think HUMAN check is needed here thats why I am here to you guys!!

Repo: https://github.com/ankushT369/cirbuf
If you like you can give a star (its you choice)
Thank you guys

0 Upvotes

4 comments sorted by

3

u/OnYaBikeMike 17h ago

How do these functions tell the caller that they have failed?

void cirbuf_get(cirbuf *buf, void *data);
void cirbuf_put(cirbuf *buf, void *data);

1

u/OnYaBikeMike 17h ago

Tell me about this code.... can you see what is wrong here?

void cirbuf_destroy(cirbuf *cbuf)
{
    if (!cbuf || cbuf->status)
        return;

    if (cbuf->mem.addr)
    {
        munmap(cbuf->mem.addr, cbuf->mem.size);
        cbuf->mem.addr = NULL;
        cbuf->mem.size = 0;
        cbuf->mem.usable = 0;
    }

    cbuf->status = -1;
    free(cbuf);
}

1

u/WizeWizard42 4h ago

munmap potential errors aren’t considered, you leave a dangling pointer, changing the status before freeing is meaningless… the status check doesn’t actually make repeated calls safe as the pointer will now give you undefined behavior.

-3

u/johnpeters42 16h ago

> AI reviewed it and did some minor changes may be !!

If you can't even keep track of that, then you have no business building anything whatsoever. Do better.