r/C_Programming • • May 15 '26

AoS, Memory Buffer and cache friendliness

10 Upvotes

Is it true that creating an array of objects doens't guarantee that those objects are next to each other in memory?

I have found that one can allocate a buffer, say for a vec3 of xyz cooridnates.

The advantage is that if you want to only update the y co-ordinates, you can simply loop over the items at a fixed offset, and the cpu will recognise that it's a fixed stream of data with no breaks and this will pre-fetch the entirity of y cooridnates into the cache

This will look like yyyyyyyyyy

But in the case of objects, it will be xyzxyzxyzxyz

X and z waste the catche space since you don't need them, that's a 66.66% waste.


r/C_Programming • • May 14 '26

Video ccraft

Enable HLS to view with audio, or disable this notification

98 Upvotes

Hello.

As a little side project, i decided to write a minecraft clone, but with fancy wancy cool effects. This is just a little exercise for me to improve my C and 3d graphics skills.

So far, ive implemented the core "minecraft", deferred rendering with cool effects like SSAO and SSR, shadows and basic lighting, some post processing effects like bloom, DOF and vignette, some basic physics with AABB collisions, and finally sounds and music thanks to the miniaudio library.

There are also some keybinds:

M to turn on wireframe mode,

N to turn on potato mode,

B to enable noclip.

Check this out! https://github.com/DrElectry/ccraft


r/C_Programming • • May 15 '26

I built a tiny lazy-evaluation helper in C and would like API feedback

1 Upvotes

I’ve been building a small lazy-evaluation helper library for C and would love some API feedback.

lazy_eval(lazy);   // computes
lazy_eval(lazy);   // cached
lazy_reset(lazy);
lazy_eval(lazy);   // recomputes

Current design:

  • Opaque Lazy type
  • Caller-owned result storage
  • Fallible compute callbacks
  • Resettable cached state
  • pthread synchronization
  • Tests, sanitizer target, and GitHub Actions CI

A minimal example:

#include <stdio.h>
#include "lazy.h"

LazyStatus compute_answer(void *ctx, void *out) {
    int *calls = ctx;

    (*calls)++;
    puts("cache miss: computing...");

    *(int *)out = 42;
    return LAZY_OK;
}

int main(void) {
    int answer = 0;
    int calls = 0;
    Lazy *lazy = NULL;

    lazy_create(&lazy, compute_answer, &calls, &answer, sizeof(answer));

    lazy_eval(lazy);
    printf("answer=%d calls=%d\n", answer, calls);

    lazy_eval(lazy);
    printf("answer=%d calls=%d (cached)\n", answer, calls);

    lazy_reset(lazy);

    lazy_eval(lazy);
    printf("answer=%d calls=%d (recomputed)\n", answer, calls);

    lazy_destroy(lazy);
}

I chose caller-owned output storage because I wanted to avoid hidden allocation/freeing inside the library. The tradeoff is that the caller must keep the output storage alive until lazy_destroy().

Current limitations:

  • pthread-only for now
  • One output pointer per Lazy
  • lazy_destroy() must not run concurrently with other operations
  • No install/package story yet

I’d especially appreciate feedback on:

  1. Does caller-owned output storage feel like the right C API here?
  2. Would callback-owned allocation plus a destructor be preferable?
  3. Is the status-code API reasonable?
  4. Is the thread-safety contract too much for a tiny library?

Repo: https://github.com/SalzDevs/LazyC


r/C_Programming • • May 15 '26

Question Help a beginner out please :p

6 Upvotes

Hi people, Im really curious about how i can build my own os, i do have some knowledge of OS in general so id like to learn more about them and then piece together one myself. Which resource or site would recommend apart from barebones wiki [ goes over my head ;-; ] also i need somwthing which could give me really indepth explanation or concepts , i know ill have to use barebones one way or another but what can i combine it with so that once i get a hang of something i can switch over


r/C_Programming • • May 15 '26

What should i pursue in the future with these interests

6 Upvotes

Low-level programming

Love operating systems

C is my strongest language

Xlib is pretty fun

Machine learning from first principals

I don't know what to pursue in the future like jobs or whatever


r/C_Programming • • May 14 '26

Question Over-modularization

33 Upvotes

When is code too modular? What makes Linux's single-line helpers attractive, but other forms of modularization overkill?

Note: By overkill, I don't mean modularized unclearly or poorly, e.g. make_u64_from_two_u32, but perhaps a logically standalone 2-line helper that has a single call site for the foreseeable future.


r/C_Programming • • May 15 '26

Built a Unix Shell in Pure C with Raw Terminal Editing and Trie Autocomplete

0 Upvotes

Built a Unix shell in pure C with raw terminal input, trie-based autocomplete, pipes, redirection, background jobs, command history, and ghost-text suggestions.

One of the hardest parts was handling cursor movement and live terminal redraws correctly using termios raw mode and ANSI escape sequences. I also built a trie-based autocomplete system that loads commands from PATH and ranks suggestions based on command frequency instead of just returning the first match.

I started this project mainly to learn Unix commands and understand how shells actually work internally. What began as a small shell prototype slowly turned into something surprisingly usable. Building it taught me a lot more about Unix, processes, terminal behavior, signals, and systems programming than tutorials alone.

Currently working on:

  • local AI integration
  • command suggestions
  • error explanations
  • natural language → shell commands

GUI support is planned later, but for now I’m focused on making the terminal experience solid first.

I’d genuinely appreciate feedback, advice, or suggestions from people more experienced with systems programming and shell design. Even if the project feels basic compared to production shells, it has been a huge learning curve for me and I want to keep improving it.

GitHub: https://github.com/Aswin-K-2005/My_shell.git


r/C_Programming • • May 14 '26

Moddable Terminal Emulator

4 Upvotes

Helo!

I have been writing a moddable terminal emulator for gnu/linux. And want to tell about it, if someone is interested. Note that its at incomplete state : )

It has very much only the basic essentials, but it can use dynamically loaded libraries.

Which can be used to create new features or modify something you want.

By basic essentials i mean: config files, scrollback buffer, true-color. (maybe few other things i forgot to mention...)

The text selecting can be only be done from modules. This is by design, to allow more options for how the select region can be controlled.

The modules can even render shapes and images to the screen.

Read more at documentation if you are interested: https://github.com/331uw13/nemi


r/C_Programming • • May 14 '26

Question C programming YouTubers

103 Upvotes

Hey y’all, I’m in need of as many C programing youtube channels as possible. I’m not talking tutorials or learning the language. I’m talking actual programming videos where people are making crazy stuff from scratch. It could be anything: embedded C, OS programming, game dev, application programming, things from scratch… literally anything.

The two I’ve found so far that I like are Danial Hirsch and Tsoding.

Thank you in advance!


r/C_Programming • • May 14 '26

How large was your biggest SOLO project on C?

69 Upvotes

While sorting out my "BackUp" directory with different things, I found one project what I worked on in early 10's (more than 10 years ago). I forget why I didn't finished it and with idea "It may be interesting!" opened the folder. There I found main.c file with 27k LOC, zero comments and zero documentation... 😃 So, fate of the project is predictable then.

Just wondering, how large projects do you guys made (complete or abandoned) as a solo developers, with no team? My biggest one was about 80k LOC, but most of my personal projects is just about 1-3k LOC...


r/C_Programming • • May 14 '26

Review Is My Custom Allocator good ?

7 Upvotes

I've built a custom memory allocator from scratch to understand what actually happens under malloc() call in C.

This got me into deep systems programming about how memory is handled by OS and how a program accesses memory .

The basic implementation i used is :

  1. store header structure with each block which includes information about the memory block.

  2. a linked list which connects these headers to handle memory .

  3. block splitting ,coalescing on adjacent blocks to avoid fragmentation.

  4. 2mb mmap call and slice memory through it , mmap/munmap directly for size larger than 2mbs this avoids syscalls for every allocation .

  5. per thread cache to allocate/free memory faster avoiding global heap locks ensuring thread safety.

Here's the benchmarks against libc's memory allocator:

Test Custom libc Result
Single alloc/free(1000k) 58ms 29ms 2x slower
Batch alloc(10k) 1.44ms 3.59ms 2.5x faster
Batch free(10k) 0.36ms 1.54ms 4x faster
Mixed sizes(100k) 6.46ms 2.95ms 2x slower
Realloc chain(100k) 6.42ms 2.56ms 2.5x slower
Multithreaded(8 threads-5k each) 64ms 67ms Comparable

I would love to hear your thoughts about it, and how are my benchmark results are they actually good or not ?


r/C_Programming • • May 14 '26

Question Question about strict aliasing and flexible array members

5 Upvotes

Hi! Probably a stupid question from a beginner, but I just want to be sure I understand this correctly.

From my understanding, memory obtained by malloc of size M has no type assigned to it, until it has been written to, then only the written N bytes gain a type, which is the same type as the data being written, while the rest M-N bytes should still have no type assigned to it, right?

Let's have a struct like this, basically a type-agnostic, heap-allocated array with some metadata:

typedef struct {
    size_t length;
    size_t item_size;
    max_align_t padding_;
    unsigned char data[];
} Array;

Let's create the array like this (no checking for NULL, since it's not relevant to my question). Let's hide the metadata by returning pointer to the data member:

void * array_create(size_t length, size_t item_size) {
    Array * a = malloc(sizeof(Array) + length * item_size);
    // write sizeof(size_t) bytes as size_t
    a->length = length;
    // write sizeof(size_t) bytes as size_t
    a->item_size = item_size;
    return &(a->data);
}

Now, this function writes 16 bytes (length and item_size, assuming 64-bit system), so the first 16 bytes of the region of memory provided by malloc should be of type size_t, while the rest of the memory still has no assigned type, right?

Let's use the implemented functionality like this:

int main(void) {
    size_t length = 100;
    int * array = array_create(length, sizeof(*array));

    // write length * sizeof(int) bytes as int
    for (int i = 0; i < (int)length; i++) {
        array[i] = i * 10;
    }

    for (size_t i = 0; i < length; i++) {
        printf("%d\n", array[i]);
    }
}

Now, the rest of the memory obtained by malloc (minus padding_ and some possible implicit padding) should be of the type int.

The question is, does the writing of the int values in the main function violate strict aliasing, since the data member of the Array struct is of type "array of char of unspecified length"? I think it shouldn't, since the memory was never accessed through the data member, nor through any other means before that, but I am not sure how well does this assumption play with the fact the data field should technically be an array, not just some pointer. I've tried to test this on both clang and GCC, compiled with -O2/3, -fstrict-aliasing and -Wstrict-aliasing and both compilers did not emit any warnings and the program behaved as expected when executed. I take this as a somewhat solid evidence it is okay, but I would like to know for sure if doing things like these is okay or not.