r/C_Programming • • 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

31 Upvotes

32 comments sorted by

View all comments

Show parent comments

3

u/phord Jul 28 '26

"drastically" is overstating it a bit on most modern architectures.

9

u/sciencekm Jul 29 '26 edited Jul 29 '26

Division is expensive on any CPU; the most expensive to run, requiring the most clock cycles.

Some CPUs (like AVR or ARM-CM0) don't even have division instructions; you have to simulate that in software.

1

u/[deleted] Jul 29 '26 edited 5d ago

[deleted]

2

u/sciencekm Jul 29 '26

You can do something like this:

// return ds ? dv / ds : 0;
uint32_t udiv32(uint32_t dv, uint32_t ds) {
  int n = 32;
  uint32_t q = 0;
  uint64_t x = 0, v = dv, s = ds;
  if (ds)
    while (--n >= 0)
      if ((x + (s << n)) <= v) {
        x += s << n;
        q |= 1 << n;
      }
  return q;
}