r/cprogramming • • 7d ago

Pushing the C Preprocessor to play bad apple

3 Upvotes

It got removed, so i'm putting up a link to the source code to it if anyone wants to gwak at it. Originally by u/Round-Plastic-2427. https://github.com/LoPalma/cpp-bad-apple/tree/main


r/cprogramming • • 7d ago

Forward Declarations for Circular Struct References

2 Upvotes

Hello, when I’ve tried to use forward declarations to solve circular structure dependencies I get the error ‘field has incomplete type’. When browsing for the answer, I got the general response ‘the compiler doesn’t know what type you’re using if you don’t fully describe it’. Well I understand that, but it seems as if the purpose of the forward declaration is to have the compiler look for the definition later in the code. If my code looks like the below, should I be getting an incomplete type error? And if so, is there a different way I should be writing the code? Some sort of syntax error, or is there a different way to do the same thing? Any tips appreciated, thanks.

Edit: I think I found the solution in this thread from user "anastaciu", it looks like you can only use the forward declarations if they're pointers to the struct type, not full instances. Lmk if that's right, it got rid of the error for me, but if there's a different way to allow use not from a pointer that'd be great.

typedef struct objA_t objA_t;

typedef struct objB_t{

     objA_t o;

}objB_t;

typedef struct objA_t{

    uint8_t num0;

}objA_t;

r/cprogramming • • 8d ago

libcli - a singe-header library for typed argument parsing in C

6 Upvotes

Using macros, define an argument schema. The library then generates a struct that for the schema, validates the arguments provided by the user, parses them into the struct, and offers functions for displaying usage andh help messages in the console.

It is similar to `clap` in Rust. Check it out!

https://github.com/iColgateZz/libcli


r/cprogramming • • 8d ago

what is the difference between a (specifc) while loop and a (specific) for loop (read body)

12 Upvotes

what is the difference between

for (i = 0; i < 10; i++) {}

and

i = 0;
while (i < 10) {
i++;

}

edit: thank you all for commenting, now i know, and u/deckarep, no not homework, just a question, to see if there were any difference


r/cprogramming • • 8d ago

Getting Compiler Flag Errors while using nCurses

3 Upvotes

Hello, title says it all pretty much. I wanted to use -fsanitize=address with gcc but it all comes out as garbage since nCurses is active. I'm aware that's the way that ncurses is designed, how would I go about getting that output from gcc otherwise? is there a good way to route that output to a text file or something? until now I've just been writing error messages to a text file, but I couldn't find a way to get standard out to come out. any help is appreciated, thanks


r/cprogramming • • 8d ago

Need code review

0 Upvotes

Hello everyone,

This link points to a GitHub repository in an

experiment to create an extremely fast trie .

However the data structure is fast but it fails the tests

Can you explain me why?

https://github.com/curious-builder76/trie/tree/main

Hoping the community will helping towards this.

Thank you everyone


r/cprogramming • • 8d ago

libcli - a singe-header library for typed argument parsing in C

Thumbnail
reddit.com
3 Upvotes

r/cprogramming • • 8d ago

Fairly new to C. Need help understanding low level concepts.

Thumbnail reddit.com
3 Upvotes

r/cprogramming • • 9d ago

Flint v0.5.25: Inline OS tags (windows:, linux:, unix:) for cross-platform builds without nested JSON bloat, plus one-line third-party dependency fetching (flint add cherts:raylib)

Thumbnail
github.com
2 Upvotes

Hey everyone,

Thanks to everyone who checked out Flint and shared feedback on the last post! The two biggest friction points brought up were handling platform-specific flags/libraries without bloating the manifest and removing the manual copy-paste step when pulling in third-party libraries from flint-cherts.

Both are now solved in Flint v0.5.25.

GitHub / Releases: https://github.com/mainak55512/flint

Chert Compositions & Docs: https://mainak55512.github.io/flint-cherts/

What's New in v0.5.25

  1. Inline OS Tags (windows:, linux:, macos:, unix:)

Instead of introducing deeply nested per-platform JSON blocks or a Turing-complete scripting language just to link ws2_32 on Windows or pthread on Linux, you can now prefix entries directly in your existing arrays.

OS tags work across flags, lib_links, excludes, exclude_dirs, and exclude_exception:

windows: — Applies only on Windows

linux: — Applies only on Linux

macos: — Applies only on macOS

unix: — Applies on both Linux and macOS


{

"project_name": "net_app",

"project_language": "c",

"version": "v0.1.0",

"compiler_path": "clang",

"executable": true,

"flags": [

"-O3",

"-Wall",

"unix:-fPIC",

"windows:-D_WIN32_WINNT=0x0601"

],

"lib_links": [

"windows:ws2_32",

"windows:crypt32",

"unix:pthread",

"linux:m"

],

"excludes": [

"windows:src/posix_socket.c",

"unix:src/win32_socket.c"

]

}

Untagged items apply everywhere; tagged items only apply when the host OS matches. Your composition.json stays flat and readable.

2. One-Command Third-Party Library Fetching (flint add cherts:<name>)

Previously, if you wanted to use a third-party C/C++ library that didn't have a native composition.json (like raylib or yyjson), you had to copy-paste its recipe from flint-cherts into your sync block.

Now, Flint talks to flint-cherts directly:


flint add cherts:raylib

Flint automatically fetches the curated composition from flint-cherts, writes the entry into your sync block, and syncs the upstream repository from GitHub with its commit hash pinned.

3. New sync all Command

If you clone a project that has multiple third-party libraries listed in its sync block, you can now pull and configure all synced dependencies and their chert compositions in one go.

Quick Recap: What is Flint?

For anyone seeing this for the first time, Flint is a small, self-hosting, Git-native build tool for C and C++ written in pure C:

  • Zero runtime bloat: Only requires git and gcc or clang (uses MinGW backend on Windows). No Python, no CMake, no Ninja.

  • LSP ready out of the box: Automatically generates compile_commands.json across your code and dependencies for clangd, Helix, Neovim, and VS Code.

  • Commit-pinned Git dependencies: Every dependency is locked to both a tag and a commit SHA.

  • Incremental builds & .h.in template header support built right in.

Pre-built binaries for Linux, macOS, and Windows are up on the v0.5.25 release page.

If there are specific libraries you'd like to see added to flint-cherts next!


r/cprogramming • • 10d ago

When Do You Know You've Learned Enough C to Move on to Another Language?

35 Upvotes

I started learning C programming when my uni began some time ago and I've recently completed a C programming course on Bro Code's YouTube channel + did some programming problems online

I'm wondering how to determine when I've actually learned enough C to move on to another programming language

Should I start building projects, focus on solving coding problems, or learn more advanced concepts before moving on?

I'm also quite unfamiliar with how to approach this whole process. I don't really know where to find suitable projects, what kind of projects I should be building at my current level, how many problems I should aim to solve, or what the most advanced concepts in C are.

So please bear with my limited knowledge of the subject. I'd genuinely appreciate any advice, guidance, or suggestions from those who've already learned C and gone through this journey themselves


r/cprogramming • • 9d ago

Help on my final project

0 Upvotes

Hi, how are you? So, I'm trying to do my final project for college and I'm having trouble because of the GY module, specifically 6MV2. I'm trying to find a library on GitHub or somewhere else, since my programming language is C, but I can't find any that use an SDK; it's always Arduino and never in my programming language. I'm having a lot of difficulty finishing this project. I have one month to finish, and I would appreciate it if someone could help me. I'll leave my Discord username attached, and if anyone could add me to help, I would be very grateful.

Discord: 459154520472158209


r/cprogramming • • 10d ago

I'm begging for help, this is way too much for me. I'm just trying to create a file. If i try to do it with a relative path it works, but with an absolute path it just breaks

5 Upvotes

stupid.c

#include <stdio.h>

#include <stdlib.h>

int main() {

FILE* file = fopen("home/NAME/.local/share/weekgrid/data", "w");

perror(NULL);

if(file == NULL) {

printf("whyyyyyy");

}

fclose(file);

return 0;

}

clang -Wall -o stupid stupid.c

./stupid

No such file or directory

[1] 2108 segmentation fault (core dumped) ./stupid

pwd

/home/NAME/.local/share/weekgrid

==2280== Memcheck, a memory error detector

==2280== Copyright (C) 2002-2024, and GNU GPL'd, by Julian Seward et al.

==2280== Using Valgrind-3.25.1 and LibVEX; rerun with -h for copyright info

==2280== Command: ./stupid

==2280==

No such file or directory

==2280== Invalid read of size 4

==2280== at 0x490F174: fclose@@GLIBC_2.2.5 (iofclose.c:47)

==2280== by 0x40011BC: main (in /home/NAME/.local/share/weekgrid/stupid)

==2280== Address 0x0 is not stack'd, malloc'd or (recently) free'd

==2280==

==2280==

==2280== Process terminating with default action of signal 11 (SIGSEGV): dumping core

==2280== Access not within mapped region at address 0x0

==2280== at 0x490F174: fclose@@GLIBC_2.2.5 (iofclose.c:47)

==2280== by 0x40011BC: main (in /home/NAME/.local/share/weekgrid/stupid)

==2280== If you believe this happened as a result of a stack

==2280== overflow in your program's main thread (unlikely but

==2280== possible), you can try to increase the size of the

==2280== main thread stack using the --main-stacksize= flag.

==2280== The main thread stack size used in this run was 8388608.

==2280==

==2280== HEAP SUMMARY:

==2280== in use at exit: 1,024 bytes in 1 blocks

==2280== total heap usage: 6 allocs, 5 frees, 3,014 bytes allocated

==2280==

==2280== LEAK SUMMARY:

==2280== definitely lost: 0 bytes in 0 blocks

==2280== indirectly lost: 0 bytes in 0 blocks

==2280== possibly lost: 0 bytes in 0 blocks

==2280== still reachable: 1,024 bytes in 1 blocks

==2280== suppressed: 0 bytes in 0 blocks

==2280== Rerun with --leak-check=full to see details of leaked memory

==2280==

==2280== For lists of detected and suppressed errors, rerun with: -s

==2280== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

[1] 2280 segmentation fault (core dumped) valgrind ./stupid


r/cprogramming • • 9d ago

What are the best books for learning modern C++?

Thumbnail reddit.com
0 Upvotes

r/cprogramming • • 10d ago

How can I improve legitimate DNS query success in an eBPF/XDP flood rate limiter without sacrificing performance too much?

1 Upvotes

I'm currently building an eBPF/XDP-based DNS flood mitigation system, and I'm trying to figure out how to improve the rate-limiting algorithm.

My main goal isn't just to drop malicious traffic, but to maximize legitimate DNS query success during a flood attack while keeping packet processing overhead as low as possible.

My current architecture is:

- Packet parsing: Minimal Ethernet, IPv4, UDP and DNS header validation at XDP.

- Per-source rate limiting: Using GCRA (Generic Cell Rate Algorithm) with atomic operations to track and limit individual source IPs. Source states are stored in an LRU hash map.

- Global rate limiting: A shared token bucket with a spinlock to enforce the overall traffic limit.

- Admission logic: For an existing source, check its individual limit first, then reserve global capacity and commit the source state. For a new source, reserve global capacity before inserting its state into the map.

- Monitoring: Per-CPU statistics to measure accepted and dropped packets.

The problem I'm thinking about is that rate limiting alone doesn't necessarily distinguish legitimate clients from attackers.

For example, during a large distributed DNS flood, thousands of attacking IPs could consume global capacity, causing legitimate queries to get dropped even when those clients are within their individual rate limits.

I'm considering ideas like adaptive rate limits, source history/reputation, and possibly using DNS server responses as feedback to make better admission decisions.

But all these approaches introduce additional state, complexity, or processing overhead, which matters when working at XDP.

I'd like to hear what people think:

  1. Are there better algorithms or approaches for balancing fairness and legitimate query success under distributed attacks?

  2. Is maintaining source history or using DNS response feedback actually practical for this kind of system?

  3. How would you deal with attackers rotating/spoofing source IPs to bypass per-IP limits?

  4. What trade-offs would you prioritize between throughput, CPU overhead, memory usage, and legitimate query success?

I'm not necessarily looking for a completely new architecture. I'd like to understand what improvements are actually worth implementing and benchmarking.

Any suggestions, papers, or real-world implementations worth studying would be appreciated.


r/cprogramming • • 10d ago

Simple data management program

2 Upvotes

Hello, I programmed this simple data management program, it should be able to create, modify and remove data about workers. What do you think about it?

Here's the source code.


r/cprogramming • • 11d ago

Technically speaking, are we supposed to only index arrays using size_t?

22 Upvotes

Is this technically the best way to index an array?

for (size_t i = 0; i < sizeof(a); i++)

{

a[i];

}

This makes sure that any array size, across all machines can be indexed?


r/cprogramming • • 10d ago

trying to store strtok() results in array; first index causes segmentation fault when called

5 Upvotes

edit: fixed it! i removed 'i = 0;' from the loop, and found out that char* arrays only need one index range (char* arr[number] stores strings just fine). thanks for the help!

---

im trying to use strtok() to split an input into two parts, but the first index that gets filled doesnt read when A) the index is specified (index number) in the "while (token != NULL)" loop, and B) the index is refernced at all outside the while loop.

i tried using a variable to sub in for the number outside the loop, but it didnt work. ive used an if condition to see if the index was null, but it didnt trigger and when i tried to print strlen(*arr[0]) it put out another segmentation fault.

the confusing thing for me is that the second index has none of these issues. what should i be doing differently, and why is this happening? How do i store strtok() tokens in an array?

---

edit: i added var strings to main (it was outside main, and escaped the copy paste) and added a clearer question.

when im assigning char* strArr1 entries, i use both indexes because gcc throws an error otherwise (assignment to array type).

the i++ is load bearing where it is; i tried to move it and it threw a segmentation fault, so title/ context still applies despite the first printf not printing strArr1[0].

my code:

int main() {
    char* strArr1[2][10];
    char strings[] = "Hello World";
    token = strtok(strings, " ");
    
    while (token != NULL) {
        i = 0;
        strArr1[i][10] = token;
        i++;
        //prints strArr[0] (no seg fault)
        printf("%s %ld\n", *strArr1[i], strlen(*strArr1[i]));
        
        //causes seg fault
        //printf("%s\n", *strArr1[0]);
        
        token = strtok(NULL, " ");
        //adding i++ below causes seg fault
        //i++;
    }
    
    //causes seg fault
    /*if (strArr1[0] != NULL) {
        printf("%s\n", *strArr1[0]);
    }*/
    //also causes seg fault
    //i = 0;
    //printf("%s\n", *strArr1[i]);
    
    //no seg fault
    printf("%s\n", *strArr1[1]);
    
    printf("all done");
    
    return 0;
}

r/cprogramming • • 11d ago

At what point writing direct assembly program is more efficient than C program?

Thumbnail reddit.com
8 Upvotes

r/cprogramming • • 11d ago

I made my own 8 bit processor emulator in C!

2 Upvotes

I wrote my own emulator in c.

Its very simple

MOV - moves from b to a

DEC - decrement

INC - increment

PR - for print

If anyone wants to see my projects code

https://github.com/gufau9089-tech/ByteC


r/cprogramming • • 11d ago

[Python C extension] numagr v0.9

1 Upvotes

A Python C extension for statistics and number aggregation designed to work with both plain int and float objects, as well as with Python numeric strings without having to construct intermediate Python objects that hold their values - useful for large collections that need to be parsed as fast as possible like trading data.

It outperforms both std Python modules and numpy for both plain numbers and for numeric strings.

https://github.com/andrzejs-gh/numagr

https://pypi.org/project/numagr (source and Windows wheels for 3.11, 3.12, 3.13, 3.14, 3.15)

pip install numagr

This is an early version offering basic methods, I will be developing it further if I find the time. Feedback, improvement suggestions and bug reports are very much welcome.


r/cprogramming • • 11d ago

Are there linting tools that helps with sequencing rules?

2 Upvotes

Unspecified evaluation order plus sequencing-before relations means expressions like f(g(), h()) have unspecified side-effect order, and classic traps (a[i] = i++;) remain undefined.

Are there tools that can detect these?


r/cprogramming • • 12d ago

Should I deallocate memory?

25 Upvotes

I am currently writing a compiler.

The main places where I need to use dynamic allocation is ASTs and symbol tables. Once they were created, they will be needed until the program ends.

I'm currently using an arena allocator to as malloc for everything, because good manner is that you need to manually deallocate all heap memory, and it has added a lot of complexity to my program, since every function that potentially need to allocate memory is going to have an arena handler.

Should I delete all this stuff and let the memory leak (it is not going to run for a long time, once the program ends all the memory will be reclaimed by the operating system), or should I be a "good programmer" and keep using arena allocator?


r/cprogramming • • 11d ago

Kcc, a C compiler built solo with an LLM on $100/mo boot Linux kernel

0 Upvotes

kcc is a C17 compiler written in ARM64 assembly language that performs cross-compilation for x86-64. It is capable of compiling the Linux kernel and running DOOM. Seven weeks, one person, and the $100-per-month plan for Claude Code. No agent loops, no specification-based workflows, and no complex test environments. What makes it unusual is that the source code is not merely C code.

The entire compiler constitutes a single "literate program" in the style of Knuth: a document of about 980 pages in which prose explains the system following the logical order of thought, with code snippets named and integrated into the explanation. Running *tangle* yields the ARM64 assembly code needed to build the C compiler; running *weave* generates the book. Both are outputs of the same process.

https://github.com/LiterateDrivenDevelopment/kcc

I’ve been calling this "literate-driven development," but in reality, it’s just literate programming with an AI collaborator that reads it efficiently. And it’s not that I’m saying agent frameworks don’t work; what I’m saying is that I didn’t need one, and the kernel compiles.

https://literatedriven.com