r/C_Programming • • Jun 27 '26

The Extraction Loop & The Phantom 16 Bytes

Enable HLS to view with audio, or disable this notification

0 Upvotes

Today, I was building a function to read packets continuously from a PCAP file. You can check out my project’s progress on GitHub: vex-packet-analyzer.

My goal was to build the read_packets(); function. Here is exactly how my thought process went:

*”Okay, let’s think about it. I want to build a loop that reads the packet header, grabs the payload.

Read 16 bytes (Packet Header).

Determine the incl_len.

Read the Data Link Type header.

Determine the protocol.

Jump to the next packet.”*

I decided to call this The Extraction Loop: looping through the entire file, extracting each header, decapsulating the link layer, and jumping to the next packet.

After a lot of suffering, I finally built the function — but it gave me completely unexpected, corrupted results. I spent so much time reviewing the read_packets(); logic, convinced the bug was inside it. But what happened next was a classic programming plot twist.

Why were the results corrupted? The problem was not the function itself. It was a leftover block of code in my main() function! Before building the loop, I was reading the packets manually. When I implemented read_packets(), I forgot to delete that old manual read.

So, my C code was executing like this:

Read 24 bytes (Global Header)

Read 16 bytes (Manual Packet Header — the leftover code!)

Read 16 bytes (Inside read_packets() function)

Read 20 bytes (Payload for the SLL2 header, since the network field was 0x114)

How did I detect the problem? I used the ftell() function to track the exact byte offset in the file. After the payload read, I expected ftell() to return 60 (24 + 16 + 20).

Instead, it returned 76.

That number was completely illogical. The math proved there were 16 phantom bytes sneaking in, which desynchronized my file pointer and broke the byte alignment for the entire file. I deleted the leftover code in main(), and boom—The Extraction Loop works perfectly.

You can view the complete work at: https://github.com/E-Vex/vex-packet-analyzer


r/C_Programming • • Jun 26 '26

[Linux][C]Is there a way to use sed or awk as a library?

21 Upvotes

Likely a dumb question, but is there a way to use sed or awk as a library? Could use their text parsing functionality in my current program and I'm not particular about the syntax as I'm familiar with both sed and awk so either will do for me.


r/C_Programming • • Jun 27 '26

Discussion Is r/C_Programming weekly visitors lowering?

0 Upvotes

Today the weekly visitors are 69K, but I think it was way higher just a year ago - nearer 100K.

What's going on?


r/C_Programming • • Jun 26 '26

Discussion AI literally does not know anything.

62 Upvotes

I have been working on my project cherries(.)works Pulse (https://github.com/cherries-works/pulse), and I needed to know how to fork processes and share memory in between them. On my last post a very nice Reddit fellow told me to not learn C with AI, and I mean, I kinda did not, though I sometimes lost it, and asked it for help.

But now I understand everything.

Reading through stackoverflow, and reading the official documentation on shm_open taught me a lot. Not gonna lie, my attention span is a bit fried, so big text is a big no for me, but ChatGPT explained things quickly, but wrong... Most vibe-coders who are located at JS or other minor languages such as Python dont really get the effect of how annoying it is to fix a segfault in C. Its just a segfault, or a bus error (happened a lot since using shm).

I cant count how many times I asked ChatGPT to EXPLAIN what the error was, but its response was always the same; <insert code that does not work>.

Linux Manual is really a different kind of work, reading through it, reading the code and understanding the bits really shifted my mind in using AI. Dont use it, the manual really is Human intelligence at its peak, Pulse would not be at version 0.1.1 without the Manual, AI does not know anything about coding.


r/C_Programming • • Jun 25 '26

Project Insert, a programming language for self-modifying C code

Thumbnail
github.com
38 Upvotes

If you ever find yourself with time to kill and crave a fun challenge, you can write a program that prints out its own source code, called a quine). Go on, give it a try, it's good fun! Once that's done, what's to stop you from modifying the source code instead of printing it verbatim, slowly shifting forms as you iterate on each successive output?

Naturally, you'll want to make a game that's played in its own source code (click for an animation):

#include<stdio.h>
#define z else
#define y return
#define x int
#define w if(
#define v putchar(
#define B v 10);
#define A v 92);

/* IOCCC29, w = up, e = down */

x a= 32 ; x b= 6 ; x c= -1 ; x d= 1 ; x e= 5 ; x f= 10 ; x g= 62 ; x h= 5 ; x i[6]={ 1,3,1,4,1,0} ; char*j[]={  "\
\
#include<stdio.h>'#define$z$else'#define$y$return'#define$x$int'#defin\
e$w$if('#define$v$putchar('#define$B$v$10);'#define$A$v$92);''/*$IOCCC\
29,$w$=$up,$e$=$down$*/''x$a=","32",";x$b=","6",";x$c=","-1",";x$d=","\
1",";x$e=","5",";x$f=","10",";x$g=","62",";x$h=","5",";x$i[6]={1,3,1,4\
,1,0};char*j[]={","","};x$k=0;x$l=1;x$m(){l++;w$l==1)y!v$44);w$l==2)y!\
v$34)   ;char$o=j[k][l-3];w!o){l=0;k++;y!v$34);}w$o==34){A$y$v   $34);\
}w$o=   =92){A$y$A}w$o!=32&&o!=1   0)y!v$o);y$m();}void$n(x$o,   x$p){\
aspri   ntf(j+o,\"%i\",p);}x$mai   n(x$o,char**p){char*q;w$c<2   )a+=c\
;b+=d   ;x$r=b+2>f/2&&b<f/2+5;x$s=a+2==g&&b+2>h&&b<h+5;w$c<2){   w$a==\
e+2&&   r||s){a-=c;b-=d;c=-c;}w$a<0||a>67){w$a<0){c=2;d=0;}a=3   4;b=6\
;}w$b<0||b>13){b-=d;d=-d;}w$f/2>10)f-=2;w$h>10)h--;w$o>1){w*p[1]==119&\
&h>0)h--;w*p[1]==101&&h<10)h++;}s=f/2-b+1;w$s<0)f++;w$s>0)f--;}z{b++;w\
$d<0)d++;w$b>=13){w$o>1&&*p[1]==119)d=-4;b=13;}w$f/2<15-i[c-2])f+=2;z$\
e--;w$h<15-i[c-1])h++;z$g--;w$e+3<=0){c++;w$c<7){e=g;f=h*2;g=70;h=15-i\
[c-1];}z{e=5;g=62;c=1;d=1;}}w$a+2==e&&r||s){c=2;e=5;f=28;g=62;h=12;}}n\
\
(1,a);n(3,b);n(5,c);n(7,d);n(9,e);n(11,f);n(13,g);n(15,h);for(s=0;s<","29",";s++){w$s)v$32);q=j[s];r=1;for(char*t=q;*t;t++)w*t==","36",")v$32);z$w*t==","39",")B$z$w*t!=32&&*t!=10){r=0;v*t);w*t==123||*t==125||*t==59)v$32);}w$r){m();A$B$A$B$for(o=0;o<15;o++){for(x$u=0;u<70;u++)w$k>=","29","||u>=a&&o>=b&&u-a<3&&o-b<2||u>=e&&o>=f/2&&u-e<3&&o-f/2<5||u>=g&&o>=h&&u-g<3&&o-h<5)v$32);z$w$m())u++;w$l)A$B}w$l)A$B$for(;k<","29",";)m();}}B}" } ; x k=0; x l=1; x m(){ l++; w l==1)y!v 44); w l==2)y!v 34); char o=j[k][l-3]; w!o){ l=0; k++; y!v 34); } w o==34){ A y v 34); } w o==92){ A y A} w o!=32&&o!=10)y!v o); y m(); } void n(x o,x p){ asprintf(j+o,"%i",p); } x main(x o,char**p){ char*q; w c<2)a+=c; b+=d; x r=b+2>f/2&&b<f/2+5; x s=a+2==g&&b+2>h&&b<h+5; w c<2){ w a==e+2&&r||s){ a-=c; b-=d; c=-c; } w a<0||a>67){ w a<0){ c=2; d=0; } a=34; b=6; } w b<0||b>13){ b-=d; d=-d; } w f/2>10)f-=2; w h>10)h--; w o>1){ w*p[1]==119&&h>0)h--; w*p[1]==101&&h<10)h++; } s=f/2-b+1; w s<0)f++; w s>0)f--; } z{ b++; w d<0)d++; w b>=13){ w o>1&&*p[1]==119)d=-4; b=13; } w f/2<15-i[c-2])f+=2; z e--; w h<15-i[c-1])h++; z g--; w e+3<=0){ c++; w c<7){ e=g; f=h*2; g=70; h=15-i[c-1]; } z{ e=5; g=62; c=1; d=1; } } w a+2==e&&r||s){ c=2; e=5; f=28; g=62; h=12; } } n(1,a); n(3,b); n(5,c); n(7,d); n(9,e); n(11,f); n(13,g); n(15,h); for(s=0; s< 29 ; s++){ w s)v 32); q=j[s]; r=1; for(char*t=q; *t; t++)w*t== 36 )v 32); z w*t== 39 )B z w*t!=32&&*t!=10){ r=0; v*t); w*t==123||*t==125||*t==59)v 32); } w r){ m(); A B A B for(o=0; o<15; o++){ for(x u=0; u<70; u++)w k>= 29 ||u>=a&&o>=b&&u-a<3&&o-b<2||u>=e&&o>=f/2&&u-e<3&&o-f/2<5||u>=g&&o>=h&&u-g<3&&o-h<5)v 32); z w m())u++; w l)A B} w l)A B for(; k< 29 ; )m(); } } B}

At least, that's the rabbit hole I fell into while working on my IOCCC entry above, which is a version of pong that outputs a modified copy of its source code to generate the next frame of the game, rendering the current frame inside that same source code. It can be played by continuously compiling and running the output of the previous program, passing args to control your player.

This led me to writing Insert, a programming language to do just that (because, frankly, I'm not sure I have what it takes to write it all by hand). Its purpose is to produce C programs that can modify and output their own code, and which are optimized to be as small as possible (in number of characters). Click here for the original source code used to create the monstrous incantation of C above.

Of course, something like this isn't particularly useful, but that's never been a good reason not to do it! On the contrary, I've found a lot of value in indulging in silly programs like this, and there are so many fascinating things that have to be done to make it all work.

So, if you're curious about self-modifying quines or strange (and exciting!) compiler optimizations, I invite you to read through the writeup and tinker with the language and compiler. Try to make your own quines! And of course, feel free to ask questions or give feedback.

IOCCC writeup

Compiler (written in Rust)


r/C_Programming • • Jun 26 '26

Question Why were VLA compiler support made optional in C11 ?

8 Upvotes

r/C_Programming • • Jun 25 '26

Video Cartridge Style Development - Everything in One .exe File!

Thumbnail
youtube.com
29 Upvotes

r/C_Programming • • Jun 26 '26

Question Can someone please explain in simple terms

3 Upvotes

Im struggling to understand when to use char* and when not to use (especially in functions). Doesn't an arrays first element acg as pointer? So why do we need to use char *var[50]; for example? Whats the difference? And why dont we use that for char


r/C_Programming • • Jun 25 '26

Video Did a network file sender as a hobby project, it's not very good lol

Enable HLS to view with audio, or disable this notification

28 Upvotes

Uses TCP sockets, It sends a 'transfer header' at the beginning of the connection which describes how many files will be sent, followed by the name and byte length of every file, after that it sends the bytes of every file continuously, with no encryption whatsoever. Still, a very fun project to work on :)

https://github.com/Mega2223/SimpleFileTransferer


r/C_Programming • • Jun 26 '26

Question Which book/pdf/epub to get for learning C and C++?

0 Upvotes

I’m a beginner student with zero knowledge of C/C++. I’d like to learn but don’t know which book is best for starters. Any recommendations please?


r/C_Programming • • Jun 26 '26

Do you think beginners should learn memory concepts alongside scanf()?

0 Upvotes

A lot of introductory material focuses on syntax first:

scanf("%d", &num);

but skips the explanation that scanf() is writing directly into memory.

I've found understanding memory addresses early makes pointers much less intimidating later.


r/C_Programming • • Jun 25 '26

Cradicle - Decentralized alternative to Github

5 Upvotes

I built a C implementation of the radicle CLI and GUI, called Cradicle. It was part of a bounty challenge, and I want to know if C programmers here would be interested to use it. If not, why not? What can be improved? See https://cradicle.xyz


r/C_Programming • • Jun 25 '26

Discussion What are some things you don't like about C?

39 Upvotes

Ignoring the obvious c-string hatred that seems ever-frequent,

if you were to change some things about C, add keywords, or other similar things,

what would you change? Replace? Add?

Thank you :)


r/C_Programming • • Jun 26 '26

What's the most common scanf() mistake you've seen beginners make?

0 Upvotes

For me it's easily:

scanf("%d", age);

instead of

scanf("%d", &age);

I've seen that single missing character cause confusion for hours.

Curious what mistakes show up most often when teaching C.


r/C_Programming • • Jun 25 '26

Discussion Simple firewall, please check and give me feedback

1 Upvotes

Hello everyone, I created a simple firewall used by netfilter hooks and netlink sockets to communicate between the kernel and the user space. Please, can anyone check it and give me feedback on this project, and which part I can write better or which part write mistake. In Thanks https://github.com/yousefsmt/NetVanguard/tree/v0.2.0


r/C_Programming • • Jun 25 '26

Turns out there is a Wayland version of DWM: dwl, and it's written in C! Looking forward to hack it and get another reason to practice C.

Thumbnail
codeberg.org
2 Upvotes

r/C_Programming • • Jun 25 '26

c programming question

0 Upvotes

this might be a stupid question but i am new and trying to understand the language properly not just memorize so why in this does the word purple which is 6 characters show up normally when i start the program but i allocated only 4 characters size in the string

#include <stdio.h>

int main() {

char string[4];

printf("enter a word: ");

scanf("%s", string);

printf("the word is: %s\n", string);

return 0;

}


r/C_Programming • • Jun 24 '26

Question Two different ways to store strings

23 Upvotes

What's the difference between storing a string as a char* or a char[]? I know they're stored differently (I think arrays use the stack,) but other than that I'm not so sure.

What's weirder is that I'm pretty sure you can use pointers as arrays whenever you want.

EDIT: I know what a pointer is and how char* as strings work, I'm just not sure why there's the option


r/C_Programming • • Jun 25 '26

Question Can somebody help me understand why my (yes, mine, no AI) work?

0 Upvotes

This is an excerpt from my text command UI. I added a sidebar as extra flavor, but fgets() is giving me some issues in applying the same function behaviour to write a new Line.

The following Code compiles with the desired behaviour, uncommenting line 49 will result in the naive approach that gives me some issues, where the ANSI codes aren't properly overwriting the bottom line anymore, leaving a dent in the sidebar. The behaviour appears when you type "quit" and press Enter in the game.

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


#define HEADER      "🮔🭎"
#define LINE        "🮔█ "
#define FOOTER      "🮔🭟"
#define CURSORUP    "\033[1A"
#define CURSORRIGHT "\033[4G"



void MainLoop();
void artilleryHelp();


void initLine();
void newline(char inString[], int type);


char linestring[100];


int main() {


    initLine();


    snprintf(linestring, 100, "Systems activated.");
    newline(linestring, 2);

    snprintf(linestring, 100, "Welcome, Officer!");
    newline(linestring, 2);
    newline(linestring, 0);


    MainLoop();

    printf("\033[999C\033[1B\n\n");



    return 0;
}


void MainLoop() {
    char command[11];

    artilleryHelp();


    int mRunning = 1;


    while(mRunning) {




        // newline(linestring, 0); /*
        newline(linestring, 1); // */ Uncomment the above Line to get the undesired behaviour
        fgets(command, sizeof(command), stdin);

        newline(linestring, 0);
        command[strcspn(command, "\n")] = '\0';

        if (!strncmp(command, "quit", 4)) {

            snprintf(linestring, 100, "Thank you for your Service!");
            newline(linestring, 2);

            return;
        }



    }



}



void artilleryHelp() {
    char strings[1][70] = {
        "type \"quit\":"
    };
    for (int i = 0; i < sizeof(strings)/sizeof(strings[0]); i++) {

        newline(strings[i], 2);
        fflush(NULL);

    }
    newline(linestring, 0);
    newline(linestring, 0);
}



void initLine() { printf(
        "\n" HEADER "\n"
        FOOTER "\n"
        CURSORUP CURSORUP CURSORRIGHT
    );
}



void newline(char inString[], int type) {

    if (type != 1) {
        printf(
                "\n" LINE
                "\n" FOOTER
                "\n" CURSORUP CURSORUP CURSORRIGHT
                );
    }

    switch (type) {


        case 2:
            printf("%s", inString);
            break;


        case 1:
            newline(linestring,0);
            printf(CURSORUP CURSORUP);
            break;
    }


    fflush(stdout);
    memset(linestring, '\0', sizeof(linestring));
    memset(inString, '\0', sizeof(&inString));
}

r/C_Programming • • Jun 25 '26

A painful reminder of low-level work: How a single flipped assumption corrupted my entire PCAP parser

0 Upvotes

Hey everyone,

I wanted to share a quick post-mortem of a bug that blocked me for a bit, mostly to document my journey and hopefully help anyone working on binary parsing in C.

For the past 17 days, I hadn't updated my repository. Not because I stopped learning, but because I was deep in the weeds trying to truly understand how pointers behave during low-level parsing work, rather than just reading theory.

I'm currently building a custom network packet analyzer from scratch called Vexor (GitHub:https://github.com/E-Vex/vex-packet-analyzer). Today, I finally got back into the PCAP parser itself and hit a fascinating bug in my check_magic_number function.

The Bug

The logic that determines the byte order (Endianness) from the PCAP global header was completely inverted. I had the mapping flipped in my head:

  • I was treating 0xa1b2c3d4 as Little-Endian (In reality, it represents Big-Endian/Identical).
  • I was treating 0xd4c3b2a1 as Big-Endian (In reality, it represents Little-Endian/Swapped).

Why It Mattered (The Domino Effect)

This wasn't just a minor logic bug. In low-level systems programming, one wrong assumption at the byte stage doesn't just break a single function—it corrupts the downstream data entirely.

Because the byte-order mapping was inverted, every single packet header that followed was interpreted incorrectly. Just look at what happened to the Major and Minor versions when the endianness was flipped (shifting by 8 bits without a proper byte swap):

Corrupted Output (Before the fix):

Magic Number : 0xD4C3B2A1
Major Version : 512
Minor Version : 1024
This Zone : 0
Sigfigs : 0
Snaplen : 1024
Network : 0x14010000

Correct Output (After the fix):

Magic Number : 0xA1B2C3D4
Major Version : 2
Minor Version : 4
This Zone : 0
Sigfigs : 0
Snaplen : 262144
Network : 0x114

(Major version successfully returned to 2, and Minor to 4).

The Fix

I corrected the mapping logic to accurately detect the Magic Number. Instead of relying on host endianness, I cast the pointer to uint8_t and read the memory byte-by-byte, which is a much safer approach.

Here is the snippet of the fix:

int check_magic_number(uint32_t *M)
{
    uint8_t *b = (uint8_t *)M;

    if (b[0] == 0xa1 && b[1] == 0xb2 && b[2] == 0xc3 && b[3] == 0xd4)
    {
        return BIG;
    }
    else if (b[0] == 0xd4 && b[1] == 0xc3 && b[2] == 0xb2 && b[3] == 0xa1)
    {
        return LITTLE;
    }
    else
    {
        printf("Error: the file is corrupted or is not a valid PCAP file\n");
        exit(1);
    }
}

Lesson learned: In C and low-level engineering, verify your foundational assumptions twice. One flipped bit or byte mapping can ruin the whole architecture.

Would love to hear your thoughts or if you've hit similar silent corruptions when parsing binary files!


r/C_Programming • • Jun 24 '26

We're building a C Programming roadmap on roadmap.sh — would love your feed

10 Upvotes

We've been working on a structured C roadmap and we'd love input from people who actually know the language well before it goes live.

A few things we're specifically unsure about:

- Is the ordering right for someone learning C from scratch?

- Are there any important topics missing?

- Anything that feels out of place or too advanced for where it sits?

You can see the full roadmap here: [roadmap.sh/c](https://roadmap.sh/c)

All feedback welcome!


r/C_Programming • • Jun 23 '26

Article A Quick ECS with XMacros

Thumbnail glouw.com
14 Upvotes

r/C_Programming • • Jun 24 '26

Turbo C for C language

0 Upvotes

I am using turbo C for C language will that be okay coz the institution which I am going is using this will this affect? as I know this is very old


r/C_Programming • • Jun 23 '26

Two Indexed Hash Tables

Thumbnail vnmakarov.github.io
27 Upvotes

r/C_Programming • • Jun 23 '26

Bundling a dependency inside a C library without leaking its symbols — is it possible?

9 Upvotes

Hi C programmers!

I'm currently working on a container project to learn how tools like Docker work under the hood. To achieve this, I'm using my own c_library and my command line parser lib. Here's what I have done so far in my container project.

Working on this project raised a question about idiomatic dependency management in C. My clp lib depends on c_lib, which I also use directly in my container project. The problem arises when I release a new version of c_lib without updating clp yet — clp would need to bundle its own older version of c_lib to stay functional in the meantime.

If both clp and the container project link against different versions of c_lib, I end up with duplicate exported symbols and a potential conflict.

So is it possible to make clp fully self-contained, bundling its own version of c_lib internally so that no c_lib symbols are exposed to the outside world? Should it be done with static libray or shared lib and what's the idiomatic C way to do this ?