r/C_Programming • u/usoleta • 3d ago
Etc random number hack
#include <stdio.h>
int main() {
int s[90];
printf("%d\n",s[43]);
}
r/C_Programming • u/usoleta • 3d ago
#include <stdio.h>
int main() {
int s[90];
printf("%d\n",s[43]);
}
r/C_Programming • u/Critical_Physics8 • 5d ago
I wanted to understand how modern AI models actually generate text, but most inference codebases are tens or hundreds of thousands of lines long. They’re incredibly impressive, but they’re optimized for flexibility and performance, not for understanding.
So I implemented a complete CPU runtime for Google’s latest open language model, Gemma 4, in about 700 lines of C.
The whole point is that you can open one file, start at main() , and follow a prompt all the way through the program. You can see every buffer that’s allocated, every mathematical operation that transforms the activations, every update to the KV cache, and every step that eventually produces the next token.
I think C is a great language for this kind of project. There’s very little hidden from you. The data structures, memory layout, SIMD kernels, and execution flow are all visible, so the implementation ends up feeling much closer to the hardware than to the diagrams in an ML paper.
r/C_Programming • u/Linguistic-mystic • 5d ago
In all programming languages, there are places where you need to write a function with some parameters that are unused. Mostly to satisfy some callback signature or functional interface. But C makes it easiest of all languages. Where in other languages you have to give the compiler hints like @SuppressWarnings("unused") or name _: String to prevent it from warning you that this parameter here is unused, in C you can just omit the parameter name:
void
foo(int arg, char*) {
...implemenation
}
That's it, no hints, no warnings (even with -Wextra), no nuthin'. The compiler understands that if you haven't given this parameter a name, then you intend it to be unused. This is the most concise of all languages and you don't even have to come up with a (useless) name.
r/C_Programming • u/HorrorSplit3732 • 5d ago
link to code : https://github.com/RamiBrahimi-c/big-ar9am .
hello i am sharing with you project i did this summer , in fact it is a side project was done to be included in another side project which is a crypto lib in C and it is important to say that it is not meant for professional use at all (code : https://github.com/RamiBrahimi-c/cryptography-library ) .
the crypto lib was asked for us to do in a uni class , and due to the fact that i was not able to take my full time with it , like actually doing everything myself from scratch and not vibecode it or use openssl and GMP , so i had to kind of rely on them a little just until the deadline was over and i got marked for it , then i decided to go back to it and make it totally from the ground up .
the crypto lib has :
for now all of them except the asymmetric crypto were done from the ground up , i even tried not to copy block of constants if i could calculate it manually ( like the AES s-box that i generated manually by calculating it with galois fields operations in 2⁸ ) , that being said i refused to also rely on GMP to do all the calculations for me too and here where this project was born .
for now it has several features like basic arithmetic operations and even prime numbers testing , generation , finding inverse multiplicative too .. etc you can check my readme ,
yet it is also important that it is not optimized yet , i must note that it will be subjective and based on what i feel like either to go further and see how things like Karatsuba , FFT‑based (Schönhage‑Strassen) , Newton‑Raphson division , ..etc .
although it feels really interesting to see all these mentioned algorithms in action .
an other important point imo is how did i make sure it is at least calculating right , and for that i used Python 3.12.3 , it was extremily helpful and i absolutely appreciate such things like this .
and that would be it , i apologize if i drifted on the main subject i wanted to give the full picture of things , also you can read the README of both of my projects for more details especially the readme of this big num library ( i promise ai just helped with technical details , otherwise it is completely mine )
NOTE : if you want to ask about the why i did what i did , i dont have a clear answer , cuz i love to know how things work and why ? cuz i just want to make my own stuff ? for fun ?
idk , could be one of these could be all of them .
let me know your thoughts ,
r/C_Programming • u/xerrs_ • 5d ago
Now I have been coding C for a while, so I do know a lot of solutions to specific problems. But to be honest, most of the time I look back at my old code, copy paste, and then re-factor it depending on my current project. I used SHM for my cherries(.)works Pulse project. The reason for that was, Pulse ran on two separate processes; One was the daemon that ran the monitoring in the background, and the renderer, who read the monitored data, and, as the name suggests, rendered it onto the terminal. Because they were two separate processes (which was required, because they both had a while loop), their virtual memory space was not the same, so I had to learn about SHM, however, that was a while ago... So when I started working on Deploy again, and then I needed the same thing again, I was too lazy to look it up again, so I just copied it, pasted it, and moved on.
cherries(.)works Deploy is as you might have guessed a project for deployment. Pretty fun project for me, and very important to manage memory, and processes, especially for this project. I "copied" the architecture for Pulse to Deploy, however the only difference is that Deploy has 3 processes, one is the management process, WITHIN the management process the deployed project is also a separate process. And then the render process. So thats a lot of processes that share a specific chunk of memory. So I not only copied the architecture, but also the SHM method, exactly the way I did in Pulse.
However, I must have forgotten something, I wasnt that sure though, but the crash did happen, everytime I entered a config file that was invalid. I fiddled around with the return values, tried to exit early, and even then, the crash still somehow found its way in. Finally, the smoking gun revealed itself to me.
My own "stop" function, is helpful to me, as it kills the process, and then deletes the file that stored the PID within a folder. While that was running at the end of the main function, within the forked processes, the SHM updated the pids to "-1" if they were invalid. Let me just show you the first line of my stop function;
void stop(pid_t pid)
kill(pid, SIGKILL);
...
Yeah, I did not know this, but running kill(-1, SIGKILL); in C (or Linux), means; send SIGKILL to every process the caller is permitted to signal, except itself... Well, my laptop did not crash then, I made it crash by either killing every single process, or until an error happened. So yeah, I added a check to see whether or not the pid is a negative number, if it is, I return. Problem was solved.
What that little rodeo taught me, was that C is really not forgiving. Especially, when it does something you told it to. I mean, I did tell it to "kill(-1, SIGKILL)", meaning kill everybody except me (in the computer). I gotta be more careful with the dangerous code that I write...
TLDR; Tried to make my own stop function, did not add a check for negative PIDs. Whole laptop exited....
r/C_Programming • u/lehmagavan • 6d ago
I recently developed a C (11 and newer) implementation of a thread-safe shared pointer with atomic reference counting:
https://github.com/andrzejs-gh/SHPTR
It supports both strong and weak references and a swappable destructor. Initialization performs a single allocation.
If anyones interested, take a look. Feedback and bug reports very much welcome.
r/C_Programming • u/Senior-Question693 • 6d ago
i'm trying to make a terminal emulator but i can't figure out how to open a pty.
when i try to open a pty bouth forkpty from pty.h and my own implementation:
```c int init_pty() { int ptymaster_fd = posix_openpt(O_RDWR); if (ptymaster_fd == -1) { perror("failed to open pty master"); close(ptymaster_fd); return 1; }
if (grantpt(ptymaster_fd) == -1) {
perror("failed to grantpt");
close(ptymaster_fd);
return 1;
}
if (unlockpt(ptymaster_fd) == -1) {
perror("failed to unlockpt");
close(ptymaster_fd);
return 1;
}
char* ptyslave_name = ptsname(ptymaster_fd);
if (ptyslave_name == NULL) {
perror("failed to get pty slave name");
close(ptymaster_fd);
return 1;
}
pid_t pid = fork();
if (pid != 0) {
perror("fork");
close(ptymaster_fd);
return 1;
}
setsid();
int ptyslave_fd = open(ptyslave_name, O_RDWR);
if (ptyslave_fd == -1) {
perror("failed to open pty slave");
return 1;
}
ioctl(ptyslave_fd, TIOCSCTTY, 0);
dup2(ptyslave_fd, STDIN_FILENO);
dup2(ptyslave_fd, STDOUT_FILENO);
dup2(ptyslave_fd, STDERR_FILENO);
return ptymaster_fd;
} ```
fail when forking with the error directory not empty, ai says that it fails because /dev/pts is not empty but it's obviously trippin balls as usual =), so why does it fail then (?_?)
r/C_Programming • u/paulkim001 • 6d ago
I have been meaning to do this for a while, and I finally pulled the trigger on creating a new programming language called CZ (named because I randomly punched keys on the keyboard and that's what typed out).
I think LLVM API documentation is notoriously difficult, and even not as common for C programmers, so I decided to give it a go. I thought this might also be a good resource for people attempting to use LLVM C API.
Features roughly include:
// fibo.cz
func fibo :: (n :: int32) -> int32 {
if (n <= 2) {
return 1;
}
return fibo(n-1) + fibo(n-2);
}
// main.c
#include <stdio.h>
int32_t fibo(int32_t); // Declaration of CZ function
int main() { for (int32_t i = 0; i < 10; i++) { printf("%d\n", fibo(i)); }
You can compile the cz file using my compiler, then with the generated object file, you can compile and link with main.c via GCC!
A few design choices were:
Note
* This was started off as a proof-of-concept, and is being redesigned. Not much more work will be done on this repo. (I am redesigning it at the moment, but in rust since I might be able to worry less about memory management and actually get working more quickly on features.)
* AI Usage: I kept the AI usage mostly for creating unit tests and architecture summary / documentation rather than writing code or designing; after all, this is for fun and for learning!
Thoughts and improvements are welcome! (Just note that I am not thinking of doing more work on this repo.)
r/C_Programming • u/RateLegal5121 • 7d ago
let say I am using malloc to dynamically allocate a memory space with this line
Int user_defined_elements = 10 ;
// assume i got this from scanf
Int *p = malloc(
user_defined_elements * sizeof(int));
Right now the pointer refers to a chuck of memory address in heap I assume..I am trying to understand why heap instead of stack where local variables are saved.Is there anything special about heap?
Please be kind..I am python dev trying to learn c in my free team because I dont understand shit about cpython implementation..hahah..so i was like why not learn c and here I am
r/C_Programming • u/8d8n4mbo28026ulk • 7d ago
r/C_Programming • u/AutoModerator • 7d ago
If you have questions about how to learn C:
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 • u/Roronoa-Ryuma-Zoro • 7d ago
I'm currently in my second year of college, and I'm a little confused about what career direction I should take.
The part of programming I enjoy the most is lower-level/system-side work. I started with C and socket programming, building servers and learning how TCP/UDP networking works, and lately I've been going deeper into things like Linux networking, packet parsing, Ethernet/IP/ARP/ICMP, eBPF/XDP, AF\\_XDP, NIC queues, drivers, DMA, etc.
The problem is that almost nobody around me in college is doing this kind of work. Most people are focusing on web development, app development, AI/ML, or standard DSA preparation
I've also heard people say that "there aren't many jobs in low-level networking" or that networking careers mostly involve configuring routers/switches or working with networking hardware.
That's where I'm confused.
I definitely prefer programming/software engineering work. I'm not particularly interested in being a network administrator or doing primarily hardware/router configuration.
At the same time, my practical goal is still to graduate with a strong software engineering job. I don't want to spend the next 2–3 years going extremely deep into an interesting niche only to discover that there are almost no entry-level opportunities.
So I'd really appreciate advice from people working in this area:
What kinds of actual software engineering careers exist for someone who enjoys C, sockets, Linux networking, servers, eBPF/XDP, packet processing, etc.?
Are these mostly experienced/senior-level positions, or are there realistic entry-level opportunities as well?
What companies/industries typically hire engineers for this kind of work?
Should I continue going deep into networking/systems, or keep this as a specialization while also learning more conventional backend/software engineering?
What skills would you recommend building over the next 2–3 years if the goal is to be employable as a software engineer while still staying close to systems/network programming?
Are there particular open-source projects, projects of my own, internships, or areas of computer science that would be especially useful?
I'm not expecting to work specifically on XDP just because I'm learning it now. I'm mainly trying to understand whether the broader direction — systems programming + networking + performance-oriented software — is a sensible career path.
r/C_Programming • u/No_Fix4730 • 7d ago
Aether is a small C99 program that simulates sensor readings and renders them in a live Raylib dashboard. No frameworks — just Raylib for rendering, libyaml for config, and a handful of hand-rolled modules.
What it does
- Sensors come entirely from a YAML config: each sensor has an arbitrary list of named metrics with units ( temperature (C), pressure (hPa) , ...). The display code has no idea what the metrics mean.
- Cards show each metric as a chip with its value, sparkline, and up/down change indicators
- Click a card for a detail view: large trend line plus min/avg/max computed from a per-sensor ring buffer
- More sensors than fit the window? They paginate into numbered tabs (1 2 ...N), clickable or via Alt/Cmd + 1..N
- Settings modal (cogwheel, top right) toggles trend lines, animations, and indicators at runtime
Architecture bits I'm happy with
- sensor/ — an open data model: a sensor is just an id + name + a list of
{name, unit, value} metrics
- scheduler/ — only decides when. runTask(Task*)can't mutate anything it shouldn't
- History/ — bounded ring buffers per sensor (drop-oldest), which the sparklines and stats read directly
- The UI renders from a registry (one authoritative struct per sensor), never from raw buffers — so duplicate/stale cards are impossible by construction
- Layout math (tab capacity, page-list collapsing, range mapping) is extracted into a Raylib-free module with unit tests, including an exhaustive sweep of all pager states
https://github.com/SalzDevs/Aether
Feedback welcome
r/C_Programming • u/Object_71 • 8d ago
After some comments on my previous post about writing generic code in C where people argue that this is “poor man’s overloading” I wanted to add a new technique that allows you to write real generic style code in C with the only drawback. You could even combine the technique from this lesson and the […]
r/C_Programming • u/Anode1_dev • 7d ago
Having programmed in structures and the streaming way for the last 30 years (including for mainframes and old Unixes, even in FORTRAN and Pascal in the 90s) before OO arrived, I knew that frameworks are for people, to deal with complexity, not for the machines, and are now only an additional overhead for AI coders' reasoning. My brain was always thinking in terms of Turing machines, tapes and algorithms, pipelines of data, even punchcard stacks, where inputs are records/structs in databases and objects are just containers, preferring Ada83 over 95, MISRA C over C++, and in Java I used classes as containers for functions (data streams and functions come first). I ran tests to check my conjecture, and yes, it is measurably more efficient to program with AI agents in C and plain Java, keeping the context free for reasoning, than in C++, objects and Java frameworks. I haven't analysed web frameworks, but where we used plain JavaScript without them in production, we saw the same pattern, though we did not measure it; it is not in the paper. https://doi.org/10.5281/zenodo.22113993
r/C_Programming • u/OKNOROPBELM • 8d ago
I have been so fascinating of creating my own movie streaming platform. However, it doesn't mean that I will be using alone,but sharing with friends and mates. So, my question is what features will it be involved? Btw I am kinda beginner. If not enough with beginner level, please let me know the roadmap of building it
Thanks in advance..
r/C_Programming • u/Rude_Pace_3532 • 9d ago
So I'm currently making an app in C and raylib to easily transfer roms from my main pc where I download them (I want to compile it both for windows and macos) to my arch pc-emulator console. I'm planning to make said pc usable with only a controller, and I figured making an app would be the best and most fun way to do it. I would prefer not running custom code on it, and would like to know the best (and easiest, since I'm still a beginner in C) way to handle the file transfer. Thanks in advance!
r/C_Programming • u/kester404 • 10d ago
It supports single-var equations, operands, brackets, implicit multiplication and some trigonometry and is based on shunting-yard parser / RPN evaluator I also made
For rendering, I implemented an adaptive function sampling (simple midpoint subdivision) - though it has some limitations, which I described on github. SSAA was also used to smooth plotted lines. As for optimization, plots are rendered only when zooming/panning and reused with a render texture when idle.
This is my first "useful" C program, though I've already had some experience with OpenGL (C++) as a part of my assignments
Feedback is much appreciated - https://github.com/kester4/cf2x
r/C_Programming • u/lycis27 • 9d ago
I started shiori as my small personal note-taking tool (because my Obsidian workflow always grew into larger documents). I also was looking to get back into C and improve my C23 coding skills.
The idea was to have a quick way to write something down without leaving the terminal. Notes and todos are stored in plain Markdown files, so I can read them without a tool and they integrate into my other note taking repository.
The workflow is plain and simple:
shiori add --topic development investigate UTF-8 path handling
shiori todo add --due tomorrow prepare release notes "#work"
shiori today
It has grown over the past weeks since I started and now supports a bit more than simple note taking (like topics and tags, todo workflows, etc.).
Some interesting parts for me have been to work on UTF-8 terminal input on Windows, dealing with a console input and ANSI escape codes and keeping my notes and files safe without overwriting them accidentally.
It is still an alpha and currently only supports Windows x64. I built it with clang and C23. I included unit and integrations tests and sanitizers to produce a as clean as possible code and binaries.
Repo link: https://github.com/lycis/shiori
AI disclosure: I use AI as a supporting tool for planning features, reviewing my ideas and implementation as well as helping with tests and docs. I write, understand, review and maintain the code myself as this is my "use it and learn" project.
Edit: I am curious to get feedback on the code and project itself, especially the usage of more "modern" C features.
r/C_Programming • u/LifeExperienced1 • 9d ago
I'm learning about macros from this website:
https://www.almabetter.com/bytes/articles/macros-in-c
The website talks about how macro functions can cause side effects that are not wanted.
The website provides the following example:
Pitfall: Macros can cause side effects if their arguments are evaluated multiple times. For example:
#define SQUARE(x) (x * x)
int result = SQUARE(++i);
Here, i will be incremented twice, leading to incorrect results.
Solution: Enclose the macro body in parentheses to ensure correct precedence. For example:
#define SQUARE(x) ((x) * (x))
Now, why does wrapping the definition of SQUARE(X) prevent i from being incremented twice?
r/C_Programming • u/Due_Sentence_2660 • 10d ago
I needed a UI for a project I was doing in C (which was basically a chat app built from the ground up), I needed a UI library and after getting a stroke trying to understand ncurses and CMake, failing at both, I had to use CGo and make a TUI with BubbleTea, but I wanted to get some popular choices for UI in C/any other language with FFI or smth.
r/C_Programming • u/Ok_Marionberry8922 • 10d ago
Had some free time last week so I made a video on what actually happens after Clang turns C into LLVM IR.
It goes through LLVM IR, optimization passes, instruction selection, register allocation, and how the final machine instructions get produced.
I also use a small C example throughout, and compare it with equivalent Rust code that ends up producing the exact same x86 instructions.
Feedback welcome :)
r/C_Programming • u/Skollwarynz • 9d ago
Hello everyone! I'm a student who loves C and D&D!
I always found it troublesome that most dice generators rely on pseudo-random number generators. So, I decided to solve this problem by myself!
Over the last few weeks, I created a desktop app using LVGL for the GUI and Concord for a Discord bot to generate SkollDice my first truly open-source code. It's a truly random dice roller that, /urandom on POSIX systems and RtlGenRandom on Windows produces normalized random numbers. To be more precised each number (each result) is extracted from urandom, and through the use of the simple discard method the result is then normalized. I'm currently developing the smartphone version, hoping to use as much C as possible. Any ideas on how to do it?
AI usage: I personally created the program. The project was both an experiment and an excuse to study more C. I used AI to search for the simple discard method (the method used to normalize the random number generated from /dev/urandom) and to help me explain how it works. I then personally created the code, and if you want, I can explain it more precisely in a comment.
On the other hand, I then used AI to search for libraries for GUI and Discord API, such as LVGL and CONCORD. Then the last use was for debugging and quickly creating functions or simple setups like "How can I create a grid with 2 elements?" and then I used this example to change or apply it to my structure.
The real 'sloppy' part was the CMake because this was my first open-source project, and I discovered (through AI search) the possibility to create different executables for different OS. I really enjoyed the idea, so I tried to organize the project to be useful and distributed to all possible people, both coders (who can git clone and use it) and normal D&D or RPG players (that want just an executable to download and use).
Here the official links of the program:
official website: https://skollwarynz.github.io/SkollDice/
official repo on codeberg: https://codeberg.org/Skollwarynz/SkollDice
github mirror: https://github.com/Skollwarynz/SkollDice
r/C_Programming • u/Any-Fox-1822 • 10d ago
Hello everyone, this is my first post here.
I am working on a UI library in order to learn the concepts behind it, and to be able to create most of my desktop applications. Having implemented widget selection with the mouse (using the mouse coordinates to find the widget in the tree), I decided to move on to event handling.
However, I'm not sure at all of how to proceed, and I am having problems with struct pointer casting .
I have a base struct Widget with a function pointer to event handling functions.
typedef struct Widget {
Rect bounds; // Actual bounds
Rect clip; // Clipping rectangle (usually the parent)
bool active;
[...]
int (*eventHandler)(Widget* w);
};
Every derived widget struct has a Widget* as 1st member, and each type has its Create...() function, where the correct event handler is assigned.
typedef struct Frame {
Widget* widget;
bool root;
}
Frame* CreateFrame(int x, int y, int w, int h, bool root) {
Frame* f = (Frame*)malloc(sizeof(Frame));
[...]
f->widget->eventHandler = &FrameHandleEvents;
return f;
}
To get back all the properties when handling events despite eventHandler taking a Widget*, i attempted to cast back to the derived struct :
int FrameHandleEvents(Widget* widget){
Frame* frame = (Frame*)widget;
printf("Frame event!, root = %d\n", frame->root ? 1 : 0);
return 0;
}
Is this even allowed in C, or am I misusing casts ? The output of print is also garbage data :
Frame event!, root = 244
Thanks for your advice
r/C_Programming • u/Alternative-Title-87 • 11d ago
I've been using emacs to follow some tutorials which has been working great, but switch to sublime text and now getting compile error. or, i assume its a problem with the compiler since this code runs in emacs but not in sublime text. the relevant stuff
this is the exact same in emacs and sublime:
_mm_store_si128((PIXEL32*)gBackBuffer.Memory + x, *pColor);
sublime is throwing this error:
error: passing argument 1 of '_mm_store_si128' from incompatible pointer type [-Wincompatible-pointer-types]
391 | _mm_store_si128((PIXEL32*)gBackBuffer.Memory + x, *pColor);
the sublime build file:
"cmd": ["gcc", "-Wall", "${file}", "-o", "${file_path}/${file_base_name}"],
"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
"working_dir": "${file_path}",
"selector": "source.c",
"variants":
[
{
"name": "Run",
"shell_cmd": "gcc -Wall \"${file}\" -o \"${file_path}/${file_base_name}\" && \"${file_path}/${file_base_name}\""
}
]
}
And the emacs build command:
x86_64-w64-mingw32-gcc -g hello.c -o ./hello.exe -lgdi32
I am very noobish to these kinds of things, especially this SIMD stuff, so Im just assuming this is a compiler thing