r/C_Programming • u/ankush2324235 • Jul 28 '26
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
View all comments
Show parent comment
6
u/ewmailing Jul 29 '26 edited Jul 29 '26
I see this implementation is centered around mmap. Is this implementation using the technique to use the underlying page mapping system to get fast and free automatic circular buffers?
If so, this is actually very popular for high performance ring buffers, like for audio and game programming. One of the advantages of this is it uses the CPU's built-in address translation hardware. I think implementations can also remove some if-checks for things like wrapping checks, so they can then avoid branch-prediction misses and even be vectorized.
Here's one write up on it, which quotes Wikipedia on the technique.
https://lo.calho.st/posts/black-magic-buffer/
And this is Casey Muratori's presentation on Powerful Page Mapping Techniques, which includes Automatic Circular Buffers.
https://www.computerenhance.com/p/powerful-page-mapping-techniques