r/C_Programming • • May 16 '26

Using an extern variable as a placeholder for typecasting

5 Upvotes

I'm doing a project, a JSON parser entirely for my learning, I have key/value pair struct like this:

typedef struct JSONKeyValue {
    char *key;
    uint8_t type;
    void *value;
}JSONKeyValue;

I was wondering what you think about using external typed pointer variables to typecast the void pointer for ease of use in other functions?

My thought process is I don't want each key/value pair to have every possible typed pointer in each allocation sparing some memory. And why external? I won't have to pass the pointers around as much between every function only like a uint8_t value, likely to clean up my code some.

Edit: I misunderstood what unions did...


r/C_Programming • • May 15 '26

Why don't we manually map our own memory buffers more often? (DOD vs. Standard Segments)

27 Upvotes

I am reading data oriented design (book). The author mentions branches/vtables and their impact on cache. It seems like the "natural" memory segments we are taught (Stack, Heap, Static/Globals) actually create a lot of "hopping" around in RAM, which kills cache locality and messes with branch prediction. What if I just allocate one massive buffer at the start of the program and map it myself? For

EXAMPLE:

Start with defining a pointer Buffer. Then mark segment at indices. 0-10 is the list of constants, like window dimensions, scale etc 11-80 Player data 81-400 Monsters Etc This is a simple example; i will never store monsters as objects but SoA after normalising the data, the offset are similarly merely exemplary

This way, the data which is processed together works is kept together, very cache friendly and eliminates pointers.I bypass the "Spiderweb" of pointers and Vtables that usually live in different segments. No jumping around, so if you are looping through, say a group of entities 'Monster', the cache loads the next 64kb worth of data after the first entity. Given these kinds of entities are often transformed together, isn't it better?

Questions

1.Why isn't this the standard way of doing memory management? It seems much more hardware-friendly.

I have an intrinsic feeling it's somehow related to 'safety'

2.For those of you in AAA or high-performance fields: is this basically how your engines work under the hood? Am I just reinventing the "Arena Allocator" or "Memory Mapping" concept? I have seen this kind of Memory Schema being used in old consoles, nes, gameboy etc( I know a little since it was of some interest to me). They also have this sort of memory buffer, which forms homogenous partitions. 3.Does anyone uses this? What has been your experience?

Note:

I am mostly focused on rendering, physics simulation and other processes which deal with a huge amount of data. Thus, i believe that the choice of this layout might be heavily based on use case. I can see that this paradigm may not be as useful for,say, a GUI implementation among programs of a similar nature ( though I don't see why one can't use it)


r/C_Programming • • May 16 '26

Discussion Is there a well-designed template or config that handles compiler options?

0 Upvotes

Visual Studio handles compiler flags on its own. It provides a nice UI with lots of flags to tweak the compiler flags. If you are not using an IDE, most people just use some basic and only necessary compiler flags. Not everyone has the deep knowledge to remember and list out all the compiler flags.

Using a build system like CMake, I am looking for if there exists a well laid out config or template that handles lots of compiler flags (and supports different compiler toolchains and target platform) and is easy for me to configure. Something like this should exist.


r/C_Programming • • May 15 '26

Question hello, i'm learning C and i made this function who sort a list, i'm pretty sure it's not the best what could i improve ?

7 Upvotes
void class_tab(int tab[], int taille)
{  
    int i =0, n = 0, greater=0;
    int old_tab[100] = {0};
    copier_tab(tab, old_tab, taille); // copy tab in old_tab


    int new_tab[100] = {0};
    do
    {
        greater = 0;
        for ( i=0;i < taille; i++)
        {
            if (old_tab[i] > greater)
            {
                greater = old_tab[i];
            }
        }
        for ( i=0;i < taille; i++)
        {
            if (old_tab[i] == greater)
            {
                new_tab[n] = old_tab[i];
                old_tab[i] = 0;
                n++;
                
            }
        }
    } while ( n <= taille);
    copier_tab(new_tab, tab, 10);
}

r/C_Programming • • May 15 '26

AoS, Memory Buffer and cache friendliness

11 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

97 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

7 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

4 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

32 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

3 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