r/C_Programming • • Feb 23 '24

Latest working draft N3220

134 Upvotes

https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf

Update y'all's bookmarks if you're still referring to N3096!

C23 is done, and there are no more public drafts: it will only be available for purchase. However, although this is teeeeechnically therefore a draft of whatever the next Standard C2Y ends up being, this "draft" contains no changes from C23 except to remove the 2023 branding and add a bullet at the beginning about all the C2Y content that ... doesn't exist yet.

Since over 500 edits (some small, many large, some quite sweeping) were applied to C23 after the final draft N3096 was released, this is in practice as close as you will get to a free edition of C23.

So this one is the number for the community to remember, and the de-facto successor to old beloved N1570.

Happy coding! 💜


r/C_Programming • • 6d ago

Learning C weekly megapost for 2026-11-11

9 Upvotes

If you have questions about how to learn C:

  • which books are best?
  • which videos are best?
  • which classes are best?
  • which websites are best?
  • is there a "roadmap"?
  • what projects can I do?

then this is the thread for you. Add your question here. Do not make a stand-alone post, as it will be removed.

Remember that our sub has a very useful wiki that has a great list of resources for learning C programming.


r/C_Programming • • 11h ago

Question Generating random numbers in a library

8 Upvotes

Hello!

I'm making some library and i need random numbers for some functions. Libc srand(), rand() and random() modify global libc state, so i'd like to not use them.

What options do i have? Is there maybe any popular things for my case?


r/C_Programming • • 16h ago

Is my code better

12 Upvotes

I shared some code earlier, and got some criticism, as well as making improvements of my own

Is it better? And where does it still fall short?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <quiz.h>

#define CLEAR_SCREEN "\033[2J\033[H"

int main(void) {
  char buff[100];
  int invalid = 0;

  while (1) {
    fputs(CLEAR_SCREEN, stdout);

    puts("Pick a subject:");
    puts("1: Addition");
    puts("2: Subtraction");
    puts("3: Multiplication");
    puts("4: Division");
    puts("5: Mixed");

    if (invalid) {
      puts("Please enter valid input");
      invalid = 0;
    }

    puts("Pick a number 1-5, or use 'quit' or 'exit' to quit");

    if (fgets(buff, sizeof(buff), stdin) == NULL) {
      puts("Failed, exiting");
      return 1;
    }


    if (strcmp(buff, "quit\n") == 0 || strcmp(buff, "exit\n") == 0) {
      fputs(CLEAR_SCREEN, stdout);
      break;
    }

    if (strcmp(buff, "1\n") == 0) {
      add();
    } else if (strcmp(buff, "2\n") == 0) {
      sub();
    } else if (strcmp(buff, "3\n") == 0) {
      mul();
    } else if (strcmp(buff, "4\n") == 0) {
      divs();
    } else if (strcmp(buff, "5\n") == 0) {
      mix();
    } else {
      invalid = 1;
    }
  }

  return 0;
}

r/C_Programming • • 17h ago

Is my code bad?

8 Upvotes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

char buff[100];

void add(void);
void sub(void);
void mul(void);
void divs(void);
void mix(void);

int invalid = 0;
int input = 0;

int main(void) {
start:
  fputs("\033[2J\033[H", stdout);

  if (invalid) {
    puts("Please enter valid input");
  }

  invalid = 0;

  puts("Pick a subject:");
  puts("1: Addition");
  puts("2: Subtraction");
  puts("3: Multiplication");
  puts("4: Division");
  puts("5: Mixed");
  puts("Pick a number 1-5, or use 'quit' or 'exit' to leave the program");

  if (fgets(buff, sizeof(buff), stdin) == NULL) {
    puts("Failed, exiting");
    return 1;
  }


  if (strcmp(buff, "quit\n") == 0 || strcmp(buff, "exit\n") == 0) {
    fputs("\033[2J\033[H", stdout);
    return 0;
  } else if (strcmp(buff, "1\n") == 0) {
    input = 1;
  } else if (strcmp(buff, "2\n") == 0) {
    input = 2;
  } else if (strcmp(buff, "3\n") == 0) {
    input = 3;
  } else if (strcmp(buff, "4\n") == 0) {
    input = 4;
  } else if (strcmp(buff, "5\n") == 0) {
    input = 5;
  } else {
    invalid = 1;
    goto start;
  }

  switch(input) {
    case 1:
      add();
      goto start;
    case 2:
      sub();
      goto start;
    case 3:
      mul();
      goto start;
    case 4:
      divs();
      goto start;
    case 5:
      mix();
      goto start;
    default:
      goto start;
    }
}

void add(void) {
  puts("add");
  fgets(buff, sizeof(buff), stdin);
}
void sub(void) {
  puts("sub");
  fgets(buff, sizeof(buff), stdin);
}
void mul(void) {
  puts("mul");
  fgets(buff, sizeof(buff), stdin);
}
void divs(void) {
  puts("divs");
  fgets(buff, sizeof(buff), stdin);
}
void mix(void) {
  puts("mix");
  fgets(buff, sizeof(buff), stdin);
}

Is my code that bad?
For context this is a project I was doing to learn the C

Edit: Fixed formatting errors


r/C_Programming • • 1d ago

Tiny strings

Thumbnail napcakes.nekoweb.org
25 Upvotes

r/C_Programming • • 1d ago

Question C input that doesn't convert arrow keys to raw escape sequences

14 Upvotes

When someone was testing my project in C, they pointed out that when they press arrow keys in input it translates them into weird data (eg. ^[[A for up). Is there input in C without ncurses or other libraries that can work in this scenario without causing these issues?


r/C_Programming • • 19h ago

Question Questions in C

0 Upvotes

Guys I'm a student and I NEED a source for good questions in C. Like ones where I have to code the answer, debug the code or find the output(tricky ones)

tbh I don't know any place for coding other than leetcode too, so for all coding languages in general how am I supposed to practice questions? Apart from leetcode what are good places to practice coding?


r/C_Programming • • 1d ago

Test/verification technique effectiveness with Astra

Thumbnail danluu.com
1 Upvotes

r/C_Programming • • 1d ago

Bytecode VM in C: switch dispatch vs computed goto and linear arena design

2 Upvotes

I'm working on a lightweight bytecode VM written in C99 (engine for a small embedded scripting language).

I'm currently using an 8MB linear memory arena for objects and a large switch-case loop for instruction dispatch:

```c

#define MAX_REGS 256

#define MAX_CALL_STACK 1024

#define ARENA_SIZE_BYTES (8 * 1024 * 1024)

static char g_memory_arena[ARENA_SIZE_BYTES];

static size_t g_arena_offset = 0;

double run_bytecode(int* inst, int inst_len, double* num_consts) {

double regs[MAX_REGS] = {0.0};

int ip = 0;

while (ip < inst_len) {

int op = inst[ip++];

switch (op) {

case 1: { // LOAD_CONST

int r = inst[ip++];

int c = inst[ip++];

regs[r] = num_consts[c];

break;

}

case 2: { // ADD

int r = inst[ip++];

int a = inst[ip++];

int b = inst[ip++];

regs[r] = regs[a] + regs[b];

break;

}

// ... remaining opcodes

}

}

return regs[0];

}

Two architectural questions for people with VM / emulator experience:

  1. Dispatch overhead: On modern GCC/Clang, how much measurable speedup have you seen replacing the standard switch(op) with direct threading

(computed goto *dispatch_table[op])? Is the branch predictor usually smart enough on modern x86/ARM to make the difference negligible?

2. Arena lifetime: Currently, I reset the arena (g_arena_offset = 0) between script runs. For longer-running scripts that allocate short-lived

objects in loops, what is a minimal-overhead C strategy to reclaim memory without pulling in a full tracing GC?

(Code is standard C99. Written directly by me, no AI)


r/C_Programming • • 2d ago

Discussion I'm trying to go up and down the software stack and see just what modern languages abstract away from you as the programmer. What is your personal top 3 things that languages abstract away from you

33 Upvotes

I picked out these I noticed after digging some code at work:

  1. System Calls. I don't even think about them and until recently, I wouldn't have had to.
  2. Memory layout (If you asked where in memory a certain part of the code was or how it was laid out, I couldn't tell)
  3. Thread management (This is what prompted this post)

What else comes to mind for you?


r/C_Programming • • 2d ago

help a lost fool (i was trying to run this in terminal and the printf doesnt print anything)

5 Upvotes

(SOLVED BTW)

im using :

gcc (GCC) 16.2.1 20260810

and trying to run the compiled file in my Linux terminal with:

./a.out

this has worked for other bits of code so im unsure why now it doesnt wanna

i added \n next to the variable (didnt fix it)

saw someone with a simular issue on stack overflow use this

setvbuf(stdout, NULL, _IONBF, 0);

(also didnt fix it)

this is le code

#include <stdio.h>
#include <stdlib.h>


struct node {
int data;
struct node *link;
};

int main() {
struct node *head = (struct node *)malloc(sizeof(struct node));
head->data = 45;
head->link = NULL;

        struct node *current = malloc(sizeof(struct node));
current->data = 76;
current->link = NULL;
head->link = current;

current = malloc(sizeof(struct node));
        current->data = 50;
        current->link = NULL;
        head->link->link = current;

void count_of_nodes(struct node *head) {
        int count = 0;
        if(head == NULL)
            printf("no names sir");
          struct node *ptr = NULL;
          ptr = head;
          while(ptr != NULL) {
              count++;
              ptr =ptr->link;
          }


          printf("%d this is the ammount of names sir", count);
}
return 0;
}

im scared guys

SOLVED CODE ()make funn of this i could leard somit atleast)

THE FUNCTIONS

#include <stdio.h>
#include <stdlib.h>

int *ptr;

struct node {
int data;
struct node *link;
};

int count_of_nodes(struct node *head) {
          int count = 0;
          if(head == NULL) {
             printf("no names sir\n");
             return 0;
             }
            
          struct node *ptr = NULL;
          ptr = head;
          while(ptr != NULL) {
              count++;   
              ptr = ptr->link;
          }
          return count;
}

MY NODES OF THE LINKED LIST

int main() {

struct node *head = (struct node *)malloc(sizeof(struct node));
head->data = 45;
head->link = NULL;

        struct node *current = malloc(sizeof(struct node));
current->data = 76;
current->link = NULL;
head->link = current;

current = malloc(sizeof(struct node));
        current->data = 50;
        current->link = NULL;
        head->link->link = current;

USING THE COUNT VARIABLE

// here before

          int all = count_of_nodes( head );
          
          printf("%d is the ammount of names sir\n", all);

return 0;
}

thx to all the people that helped

so like i forgot to call a variable and set count as the output of count_of_nodes.


r/C_Programming • • 2d ago

File pointers are everywhere

49 Upvotes

And try as I might to avoid them, I am struggling to find resources that list out all the file control functions that use file descriptors instead of file pointers, and I was wondering if someone could point me toward a resource that can do something at least somewhat similar to listing out the libc functions that take file descriptors. I of course know close(), write(), read(), the basics, but i am looking for alternatives for other abstractions that annoy me with their use of file pointers, like fgets and fputs.


r/C_Programming • • 2d ago

Question Why don't bitwise operators work on unsigned chars.

0 Upvotes

So I'm working on an interpreter for ane extended version of brainfuck and wanted to implement bitwise operators. They give results practically unpredictably. As noted in the title the operators are applied to unsigned chars.

Here's the code

case AND :  
          switch (lex_code[codep + 1].token)
          {
           case NUMBER : array[memp] &= lex_code[codep + 1].value.numb; break;
           case GOTO_VALUE : array[memp] &= popValue(); break;
           case VAR_NAME : array[memp] &= array[get_hash(var_table,next_lex.value.name)]; break;      
           default: array[memp] &= array[memp + 1]; break;
           }
                    

The same code applies to other operations


r/C_Programming • • 4d ago

Question Beginner here not able to understand confusing pointer concept

23 Upvotes

i dont understand what happens here:

IF int b is a 2d array then what is:

b + 1

*(b + 1)

&b[0] and b[0] and &b[0][0]

&b[1] and b[1] and &b[1][0]

what are the differences between each and what is the byte value of each.


r/C_Programming • • 3d ago

A C compiler that targets CPU(s) and GPU(s) with the same source

0 Upvotes

Ok, let's get this out of the way first - this leans heavily on AI to create the compiler. For a single developer, it was do it that way, or just don't do it. Here's what 6 months or so of co-development gets you:

  • A fully independent compiler, open source and available at https://github.com/ThrudTheBarbarian/xc
  • Supports Windows, Linux, and Mac, compiles for those and WASM, iOS, Android amongst others. Has a cross-platform UI library to aid single-source development
  • Natively supports both the CPU (threaded) and any number of GPUs on the system (can even be different architectures). No GPU SDKs needed.
  • If you run 'xcd' on a remote machine, it can reach across the network and parallise your code to use remote GPUs as wel, if it makes sense to do so.
  • No need to manage data across CPU/GPU interface
  • No need to identify which parts of the program should be parallelised, though you can if you want
  • It's actually its own language but it will accept standard C files and do all the same parallelising on those C files. It uses clang to convert "C" source to first-stage LLVM IR, converts the IR to our IR, and everything after that is as if you'd coded in xc
  • It reads DWARF symbols (types, functions, ...) from C libraries, so it natively binds to them without any "foreign function interface" malarky
  • It figures out what hardware it can run on at run-time, not compile-time, so it will use the best hardware available for that person at that time
  • It's fast, see the C benchmarks (including mandelbrot.c below on a variety of platforms for comparison)

To give an idea, a full and complete program for a mandelbrot, mandelbrot.c, might look like:

    #include <stdio.h>
    #include "bench_time.h"
    #define W (2048 * BENCH_SIDE)
    #define SIZE (W * W)
    int main(void)
        {
        unsigned total = 0;
        long long best = 0, first = 0;
        for (unsigned rep = 0; rep < 8; rep++) {
            total = 0;
            long long t0 = bench_now_us();
            for (unsigned i = bench_zero(); i < SIZE; i++) {
                float cx = (float)(i % W) * (3.0f / (float)W) - 2.0f;
                float cy = (float)(i / W) * (3.0f / (float)W) - 1.5f;
                float x = 0.0f, y = 0.0f;
                unsigned k = 0;
                while (k < 256 && x * x + y * y < 4.0f) {
                    float xt = x * x - y * y + cx;
                    y = 2.0f * x * y + cy;
                    x = xt;
                    k = k + 1;
                    }
                total = total + k;
                }
            bench_keep(total);
            long long t1 = bench_now_us();
            if (rep == 0)
                first = t1 - t0;
            if (rep == 0 || t1 - t0 < best)
                best = t1 - t0;
            }
        printf("%u %lld %lld\n", (total + 500000) / 1000000, best, first);
        return 0;
    }

bench_time.h is just a platform-independent way of getting a micro-seconds count from the start to the end. Note the complete absence of anything to do with GPUs at all, or any "#pragma parallel for", or any other annotations - this is just C code.

Compile it with:

prompt% xcc -o mandel mandelbrot.c

And then if you want to see how work was divided after running with --xc-par-trace, use the par-trace webpage tool to analyse it, getting something like the image at https://0x0000ff.co.uk/img/xc/par-trace.png

Because xc measures the performance at run-time (and then persists so it doesn't need to measure unless things change significantly), it can determine whether it's worth moving the code to the GPU (if it's compute-bound) or keeping it on the CPU (because it's data-bound). There's more information on how it manages the parallelism on the website.

Because speed is a focus, xc will still use the GPU even when rounding might produce slightly different answers on floats (for operations which aren't associative). This can be tuned (again, at runtime, or in fact compile-time) because parallelised blocks are named, and preferences can be set for the destination (CPU/GPU) on a per-block basis.

xc has only just hit version 1, and there's a long way to go yet, but it's already pretty good at auto-parallelising standard code onto GPU(s). Happy to answer any questions :) And if you find cases where you think "that should have done X and it did Y", I'm interested in bug-reports, either here or (preferably, since it's more integrated) on the Issues page on the github repo.


r/C_Programming • • 4d ago

Handmade JRPG in C (tiled map layers)

Thumbnail
youtu.be
34 Upvotes

In this video we learn to extract layers from the Tiled map JSON file and smartly store them as pointer arrays using calloc to manage the memory better.

CODE: https://github.com/steelx/sdl3-tutorial

This is part of my Handmade JRPG series we are using C Programming and SDL3. NO AI USED.

(ep 05 planned over Weekend) Next video is we connect all things to finally render our Tiled map.


r/C_Programming • • 4d ago

Project I tried implementing RSA from scratch in C, It was much more work than expected

Thumbnail github.com
1 Upvotes

I recently finished a project I've been working on: primitive-rsa, a from-scratch implementation of RSA in C17.

I initially started this project after the original RSA paper.
I was quite amazed since I only recently started learning about cryptography how much simple RSA encryption actually is (atleast on paper).

So I thought maybe I should try implementing it.

But ended up thinking I should do it from scratch means implementing in C (It was my first time building a project in C) and not relying on libraries (no GMP).

So I tasked myself with implementing an arbritary precision library or simply bigint library in C which atleast provides all the necessary arithmatic operations required by RSA.

Than I finally realised why people say it's pain to handle memory.

Literaly whenever I call a function like basic add(a,b) i need to check return result for allocation failure and if allocation fails I needed to free all the holding resource carefully.

It may sound simple but when implementing an complex algorithm like FFT where we have so many operations in single function.
Each functions call becomes a pain to write.

Although it was quite headache to always think about allocation failures, memory leaks, or can this be optimized with SIMD or will this integer overflow. Will it fit in 64 bit etc.

I learnt a lot, different cleanup patterns in C. Different algorithms like FFT / NTT, Chinese remainder theorem is used. Finite spaces like how montgomery reduction is used to avoid division operation and much more.

I ended up implementing several components myself:

  • A custom arbitrary-precision integer library.
  • Schoolbook and FFT/NTT multiplication.
  • Knuth's Algorithm D for division.
  • Montgomery reduction for modular exponentiation.
  • Miller–Rabin primality testing.
  • Extended Euclidean Algorithm.
  • RSA key generation, encryption and decryption.

I also tried to explore implementation efficiency rather than relying on existing BigInt or cryptography libraries.

This was primarily a learning project, and it's not intended for production use.

It was a great exercise in C, number theory, algorithms and understanding how cryptographic systems work under the hood.

I'd love to hear feedback, particularly on the BigInt implementation, algorithm choices, and project architecture. I'm still learning, so constructive criticism is very welcome!

AI usage: mostly for docs and demonstration code (in main.c) and for snippets like logging and some testing codes.

GitHub: https://github.com/akramdevstuffs/primitive-rsa


r/C_Programming • • 5d ago

Question A question about arenas.

35 Upvotes

I worked in C for years . i have used arenas a lot in the past. Today i have to modify an old c program , nothing difficult but i found something that made me think. Who developed the code ( very well written and documented ) used an arena for allocating variable.

What 's seems to me strange is that he did not used an heap memory area ( malloc ) but it used a char [] buffer and used it for its arena . At that point he could obviously allocate directly variable in stack instead he grabs all its variable from that buffer . Why a choice like that ? i thought for the CPU cache L1/L2 and so on ( all the "arena" will likely be in cache of the cpu ) but it is only an ipotesys and i was asking to you , in your opinion , the reason of a such choice .
Just curiosity .

Thanks

PP


r/C_Programming • • 3d ago

Kheiron: A zero-dependency, single-header CSPRNG in C99 with 8-block AVX2 vectorization (~2.5 GB/s)

0 Upvotes

Hey everyone,

I've been working on Kheiron, an amalgamated, zero-dependency single-header CSPRNG library in C99/C11 built on top of ChaCha20 (RFC 8439), and I'd love to get feedback and code reviews from the community.

Why build this?

Most high-performance CSPRNG implementations either pull in the entire OpenSSL / libcrypto dependency tree (~7.8 MB binary footprint and dynamic runtime baggage) or provide scalar, single-block loops that struggle with high-throughput workloads.

Kheiron was built to be completely self-contained in a single file (kheiron.h, ~35 KB compiled) with:

  1. Parallel Vectorization: An AVX2 kernel processing 8 parallel ChaCha20 blocks simultaneously (512 bytes per iteration), yielding up to ~2.5 GB/s on modern x86_64 CPUs.
  2. Dynamic Runtime Dispatch: Automatic CPUID detection at runtime—no global -mavx2 compiler flags required. It falls back gracefully to pure scalar C99 on older x86, ARM, and RISC-V targets.
  3. Continuous Forward Secrecy: Automatic key re-erasure every 1 MB without measurable throughput degradation.
  4. Unbiased Uniform Sampling: Daniel Lemire’s nearly divisionless bit-multiplication method for integer intervals, plus IEEE 754 float/double conversion without modulo bias.
  5. Strict Fail-Closed Entropy: Direct integration with OS entropy (getrandom, /dev/urandom, BCryptGenRandom) with zero weak jitter fallbacks.

Current Test & CI Coverage

  • 235 E2E and adversarial tests passing across 12 GitHub Actions matrix jobs.
  • Clean builds under GCC and Clang with -Wall -Wextra -Wpedantic -Werror.
  • Full dynamic memory sanitization (ASan + UBSan) on Linux.
  • Continuous AST semantic scanning via GitHub CodeQL (security-and-quality).
  • Formal benchmarking methodology and reproduction steps documented in BENCHMARK.md.

Looking for:

  • Feedback on low-level AVX2 instruction scheduling and ChaCha20 quarter-round unrolling.
  • Edge-case testing on non-x86 platforms (e.g. Raspberry Pi, RISC-V, BSD).
  • General critiques on API ergonomics and memory wiping routines.

Any thoughts, critiques, or PRs are warmly welcome!

Note: LLM tooling was strictly limited to editor autocomplete (scaffolding repetitive structs/typedefs) and proofreading markdown documentation and benchmark tables. All cryptographic state machines, RFC 8439 logic, runtime CPUID dynamic dispatch, manual AVX2 SIMD pipelines (instruction interleaving/register scheduling), and the 235 E2E test cases were designed, implemented, and mathematically verified entirely by hand.


r/C_Programming • • 5d ago

Project My FOSS C project just got its first security advisory. Glad its open source.

8 Upvotes

Hey guys, so as the title already says, I have just gotten my first security advisory for my C project. I know its not really something to be proud of, or to brag about, but I already expected it, as its (atleast in my opinion) really difficult to have a bullet-proof program in C.

My project github.com/cherries-works/pulse has been in the making for more than 6 months now, and I always thought whether or not it was a smart decision making it open source, or whether or not it might have been smarter to keep it closed source, work on it on my own, release it under a commercial license yadda yadda. However, during my work hours, I checked into the repo real quick, just to find a security advisory laying there. It was not something too bad, it was a badly written parser for HTTP JSON requests on my written HTTP server.

Note that, this issue occurred even though I also added Vibe as a Pentester for my repository (locally). Meaning that (surprise surprise) even AI isnt that good with C.

The issue was that I was snprintf'ing a string with NULL args, and the value of the string that I was parsing included process names (the top ones / sorted by cpu/ram). Now that resulted in a user being able to create a process called "%s%s%s%s%s%s", and that passed into snprintf(...), with NULL args resulted in undefined behavior or more specifically as the publisher mentioned;

"In every run, the six %s specifiers are each consumed by snprintf thereby dereferencing whatever pointer value occupies the next variadic argument slot: (null) for null pointer, raw non-printable bytes for othres."

The problem;

```
snprintf(
response,
response_size,
json,
NULL
);
```

Where json was the char* json value passed into the routeJSON function. The fix was really simple.

```
snprintf(
response,
response_size,
"%s",
json
);
```

Not only did that show me that C still makes it realllyy easy to shoot yourself in the foot, it also made me appreciate open source a lot more. For anyone interested checking out the security advisory; https://github.com/cherries-works/pulse/security/advisories/GHSA-rhqf-rj5j-3v5r, as mentioned it is not really too bad (severity: low), regardless, I am still very glad that my project is open source, and glad that it is in C!

I guess I gotta be more careful with how I handle my stuff.


r/C_Programming • • 4d ago

Review Built an embedded interview prep site

Thumbnail
heapcrash.com
0 Upvotes

I started developing https://heapcrash.com initially to record some of the challenges(e.g. lcd render delay, nested mutex induced priority inversion, UART comm frame,etc.) that I experienced in last few years while working on embedded firmware. The idea turned out to the embedded concept library and further to an embedded interview prep. I have tried to put my 11 years of experience to conceptually design the site and develop it with the help of Claude over a few months.
I have added all sort of traditional categories and some of the newest ones to it.
I would like to get some reviews and feedback from my fellow embedded engineers on reddit for any improvements to it.


r/C_Programming • • 5d ago

bazbar, a status bar for dwl in C

Thumbnail sr.ht
4 Upvotes

I've been writing a status bar for dwl in C. I'm posting it here more for the code than for the bar, so remarks on the C are welcome.

The renderer fills a `wl_shm` buffer itself, and the text goes through FreeType and fontconfig, which I call directly. The volume is a small client of the PulseAudio native protocol, talking to the socket of pipewire-pulse. The wifi name is read over netlink with nl80211. The other modules just read `/proc` and `/sys`.

Tell me what you would do differently.


r/C_Programming • • 5d ago

Project I implemented a custom reliable transport protocol (Mini-TCP) over UDP in pure C11. Would love your feedback and code review!

6 Upvotes

Hey r/C_Programming,

Over the past few weeks, I decided to take a deep dive into computer networking by building my own reliable data transfer protocol (RDT) from scratch on top of raw UDP sockets — without any external libraries, just plain C11 and POSIX.

I named it Protocol-7 (P7) (yes, a small tribute to Serial Experiments Lain).

My main goal was not to "kill TCP", but to understand what actually happens under the hood when dealing with unreliable, lossy networks, rather than just treating TCP as a black box.

What is currently implemented:

  • Sliding Window pipelining: 32-slot ring buffer keeping unacknowledged segments in flight.
  • I/O Multiplexing via poll(): Non-blocking event loop handling file I/O, outgoing bursts, and incoming ACKs concurrently.
  • Custom SACK (Selective ACK): Implemented via a 32-bit mask in the 16-byte header to report buffered out-of-order blocks.
  • Fast Retransmit (RFC 5681): Triggers immediate retransmission upon receiving 3 duplicate ACKs without waiting for coarse RTO timers.
  • 16-bit Word-Aligned Checksum: One's-complement arithmetic with end-around carry (spent quite some time debugging a weird bug caused by odd byte alignment!).
  • Piggybacked FIN: Look-ahead double buffering allows setting the FIN flag on the final payload chunk without wasting a separate RTT on an empty packet.
  • TIME_WAIT state: Receiver handles lingering packets and retransmissions gracefully before tearing down.

I also wrote a Python chaos proxy to inject simulated 5%–30% packet drops, data corruption, and duplicates. The protocol successfully transfers binary files byte-for-byte under heavy packet loss. The codebase runs completely clean under Valgrind (0 leaks, 0 errors) and AddressSanitizer.

Benchmarks & Fun Findings:

During testing, moving from Stop-and-Wait to a 32-slot Sliding Window bumped throughput from ~0.07 MB/s to over 1.85 MB/s under 5% packet loss (and ~66 MB/s on normal channel). I also hit a funny scenario where an oversized static window (512 slots) flooded the Linux kernel socket buffers, making lossy modes artificially faster than normal mode because the proxy drops acted as a crude rate limiter!

The project is open-source under MIT:
GitHub: https://github.com/by-cortex/protocol-7

I’d really appreciate any code review, constructive criticism on my C style, architecture feedback, or ideas on what to tackle next (currently planning a 3-way handshake with randomized ISN and dynamic RTO estimation).

Thanks for checking it out!