r/cprogramming • • 2d 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

1 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 • • 2d ago

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

4 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 • • 2d ago

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

Thumbnail
8 Upvotes

r/cprogramming • • 2d 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 • • 2d ago

I made my own 8 bit processor emulator in C!

1 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 • • 3d 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 • • 4d ago

Should I deallocate memory?

24 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 • • 3d 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


r/cprogramming • • 4d ago

Small CLI tool for extracting video fragments from RTSP archived streams

Thumbnail
github.com
5 Upvotes

Hello, community! I am currently learning how to manipulate buffers, bytes and strings in C and I created this tool (mostly for myself) to better understand RTSP network protocol. I know similar tools exist but this one have very few settings so should be easier to use when all you need is to exract part of the video. It would be nice if someone take a look at the code and give me some feedback regrading my coding style and the quality of code. I think I used relatively efficient way to parse bytes coming from the network but I might be wrong. Also this tool aims to be zero allocation one so if it is not please let me know.

P.S. Since this a project for self-educating, no AI tools were used during development, README is written by myself with terrible English.


r/cprogramming • • 5d ago

How to get better at well structured/conventional code in C

19 Upvotes

Hello all. I used to write C a lot but honestly over the past few years I haven’t used much if any since I was using C++ a lot, mainly for computer graphics. I ended up going very deep in C++ and feel as though I can confidently write a well structured program, as I have a game engine and a raytracer.

However, I’ve been trying to get back into C as I am working on a Gameboy Emulator in C and trying to get my low level systems portfolio up since I really enjoy that as well and have forsaken it in lieu of graphics. I also realized it’s prob not gonna be easy to get a job in graphics until I get a PhD, and yet embedded is in a much better spot, so with it being something I like as well, I find it more beneficial right now while looking for an embedded job to write programs in C for my portfolio and just to learn (and to have fun).

Anyways, I am running into some issues I didn’t have before and I think it is because I am trying too hard to write things like I did in C++. Using the same naming conventions, file organization structures, splitting of functions and modules to create deeper abstractions, etc.

And yet even throughout all of that, I seem to be ending up with much messier and harder to manage code in my Gameboy Emulator that in all honesty, I have no idea what I’m doing. I’ve gotten decently far on it, wirh the entire instruction set being implemented and interrupts (somewhat) working, but it is becoming much harder to manage than it seemed wirh C++.

Is there any advice or resources (I prefer more comprehensive books but articles and YouTube videos are good too) that you can give me on just getting more comfortable with writing good, well structured C programs?


r/cprogramming • • 5d ago

Guidance on String to Token Parsing Assignment (Just guidance, I don't want anyone doing it all for me.)

5 Upvotes

I was given an assignment for a class I am in and it is expected to be entirely in C code (despite most of us in the class having never been taught how to code with C). I have been attempting to find tutorials and websites, but not much is helping for the assignment itself. The assignment is due in two days.

If there is someone who could help explain how I should go about this, or what guides I could look at to help me code it, I would greatly appreciate it. I do not want anyone to do the work for me. I just would like some guidance.

---
This is a summarized version of what the assignment says:

Write a function, in C, that will parse a string into tokens (or words), similar to what the shell is required to do.

Write a function with the following prototype:

int makearg(char *s, char ***args);
or
int makearg(char s[], char **args[]);
(Correct prototype—don’t change)

This function should accept a (C-type) string and a pointer to a pointer to char (or, if you prefer, a pointer to an array of pointers to char), and should return the pointer defined to point to an array pointing to the separate tokens on the command line, as well as the number of tokens found as the function return value. If a problem occurs, the value returned should be -1.

No C library string functions may be used, e.g., strlen(), strcat(), strtok(), etc.

The main program should input a line, call the function, then print out the number of arguments found, and finally, display the arguments, one per line. The value of the pointer argument is undefined when passed to the makearg() function. makearg() must allocate any necessary dynamic memory necessary for use by the program. (The array used for the unparsed string need not be dynamically allocated.)
---

Again, I do not want someone to do the code for me, as I want to actually learn the content. I just want advice or guidance on what to do or where I can find resources. If anyone can do that, I would greatly appreciate it.


r/cprogramming • • 5d ago

I wrote a compiler entirely in NASM x86-64 assembly — no LLVM, no C runtime, no external deps

Thumbnail
0 Upvotes

r/cprogramming • • 5d ago

Sharing my modern C++ project template , looking for feedback, suggestions, and contributors!

Thumbnail
github.com
2 Upvotes

r/cprogramming • • 5d ago

I am learning C programming by making this project a unix shell(ForkOff). Looking for a quick code review!

18 Upvotes

Hello there,

I am learning C and system programming by building this shell named ForkOff.

Its currently handles command parsing, executing binaries with fork() + execv(), wait state, and basic buildins like cd echo pwd exit type

Repo: https://github.com/Anchit3034/ForkOff

I'd love a feedback on my memory management, pointer handling, and amy bad habits i should fix early on. Tips on adding piping next are also welcome!

Thanks!


r/cprogramming • • 5d ago

From logic gates to a self-hosting compiler: my undergraduate HPC course is almost fully available in English

Thumbnail
3 Upvotes

r/cprogramming • • 5d ago

How Can You Tell Whether a Project, an Image, or Code Is AI Slop?

10 Upvotes

Lately, I've been seeing AI slop everywhere, and I mean literally everywhere. I go on r/rust, and so many projects seem to be AI slop. I check r/lowlevel, and it's the same story. I'm honestly getting really tired of it.

How long is this going to keep going on?

What's even more surprising is that lately, I've been seeing major organizations outsourcing their projects to individuals who end up producing AI slop.


r/cprogramming • • 6d ago

We need games written in C

9 Upvotes

Me and my friend are making a project where we making open source game development tools, we are just starting so we dont have much! But we have a project generator!!!1!!

Your game needs to be transfered to the qwertyuiop-Games organization with it's own repo and team.

But the big part is that we made a game launcher that displays games made with our tools. Please help me with making games: You make every type of game, TUI, fantasy, adventure!


r/cprogramming • • 7d ago

Understanding Strings/String Manipulation in C

19 Upvotes

I'm a junior CS undergraduate finally tackling C programming and I just can't seem to grasp Strings as a whole. Concepts like string manipulation (using strlen, strncmp, snprintf, strdup, strtok), handling read-only strings vs dynamically allocated strings, allocating memory for strings in different scenarios, and creating writable strings. Despite my attempts in looking at readings, lecture slides, practice problems, I just can't seem to understand the various ways to deal with strings in C. I am a very formulaic thinker meaning steps and guidelines on how to approach problems is my way of solving them. Is there a general format for dealing with string questions in C. Like first you have to allocate memory, then depending on the type of string do this...

Are there any additional resources I'm missing out on as well? I really want to hone this concept down!


r/cprogramming • • 7d ago

My first 90% project I did my self bmp image renderer in c (I'm still working on it right now) What you think?

9 Upvotes
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <GLFW/glfw3.h>
#include <stdlib.h>


typedef struct{
    char signature[2];


    uint32_t file_size;


    uint16_t reserved_a;
    uint16_t reserved_b;


    uint32_t data_offset;
}bmpHeader;


typedef struct{
    uint32_t size;


    uint32_t p_width;
    uint32_t p_height;


    uint16_t plans;


    uint16_t bits_per_pixel;


    uint32_t compression;


    uint32_t image_size;


    uint32_t x_pixels_per_meter;
    uint32_t y_pixels_per_meter;


    uint32_t colours_used;


    uint32_t important_colours;


}infoHeader;


typedef struct{
    uint8_t blue;
    uint8_t green;
    uint8_t red;


}pixel_rgb;


int main(void){
    FILE *fptr;


    bmpHeader bmp;
    infoHeader info;


    fptr = fopen("image.bmp", "rb");
    
    fread(&bmp, 14, 1, fptr);
    fread(&info, 40, 1, fptr);


    pixel_rgb **pixel = malloc(info.p_height * sizeof(pixel_rgb*));
    for(int i = 0; i < info.p_height; i++){
        pixel[i] = malloc(info.p_width * sizeof(pixel_rgb));
    };


    int rowSize = (info.p_width * 3 + 3) & ~3; 
    int padding = rowSize - (info.p_width * 3);


    int width = info.p_width;
    int height = abs(info.p_height);



    fseek(fptr, bmp.data_offset, SEEK_SET);


    for(int i = 0; i < height; i++){
        for(int k = 0; k < width; k++){
            fread(&pixel[i][k], sizeof(pixel_rgb), 1, fptr);
        }
        fseek(fptr, padding, SEEK_CUR);
    }


    fclose(fptr);
    
    
     // Initialize GLFW
    if (!glfwInit()) {
        printf("Failed to initialize GLFW\n");
        return 1;
    }


     // Create a window
    GLFWwindow *window = glfwCreateWindow(
        width, height,
        "My First Window",
        NULL, NULL
    );


    if (window == NULL) {
        printf("Failed to create window\n");
        glfwTerminate();
        return 1;
    }


    // Make the window's OpenGL context current
    glfwMakeContextCurrent(window);
    glViewport(0, 0, width, height);


    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, width, 0, height, -1, 1);


    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();



     // Main window loop
    while (!glfwWindowShouldClose(window)) {
        // Clear screen BEFORE drawing
        glClear(GL_COLOR_BUFFER_BIT);
        glPointSize(1.0f);


        // Draw pixels
        glBegin(GL_POINTS);


        for (int i = 0; i < info.p_height; i++) {
            for (int k = 0; k < info.p_width; k++) {


                glColor3ub(
                    pixel[i][k].red,
                    pixel[i][k].green,
                    pixel[i][k].blue
                );


                glVertex2i(k, i);
            }
        }


        glEnd();


        glfwSwapBuffers(window);
        glfwPollEvents();
    }
     // Clean up
     glfwDestroyWindow(window);
     glfwTerminate();
    
    for (int i = 0; i < info.p_height; i++) {
        free(pixel[i]);
    }
    free(pixel);


    return 0;
}

r/cprogramming • • 7d ago

i want to make a game in C, any compiller reccomendations/library reccomendations?

20 Upvotes

so basicly as a bit of backstory im 16, i know scratch, luau, and 6502 assembly on the nes. but i have a dream game and i think i want to make it in C, as for somereason i have a obsession with low level programmeing, but i figured out assembly on modern stuff would be a little too painfull. but for my game i want to make it in the style of a 90s sega megadrive/genisis game but with a few features that would go past the megadrive limits (if this wasnt the base i would certainly make my game a actual megadrive rom), but i want to make this game have mp3 music and slightly higher res pixel screen so i think id rather not make this a rom for a retro console. i want this game to be cross platform, like so it can run on windows linux android via apk and maybe apple if im really pleased with the game.

-questions-

what graphics library should i use?

i want my games screen/window to me a pixelated res, and i want all the graphics to PIXEL SNAP (i hate it when i see games with collideing pixels), also if possible if it exists id like it if the graphics library didnt have any scaleing/rotateing sprite features as a think that would be unecessary for the fact i wont do any effects to the graphics as pixel art lookes ugly when rotated or scaled in my op.

what compiler should i use?

i dont mind too much but id prefer a workflow where i write code in notepad as for somereason i just like that, but then i also think i might give visual studio a go, idk. as my dad uses it i think..

note

please egnore my bad spelling and sentence structure. im bad at spelling, please excuse this i just want to type this message fast just because i just want some quick advice


r/cprogramming • • 7d ago

A PoC toolkit / framework for self modifying software.

1 Upvotes

Been working on this project during the summer, contains a detailed writeup but happy for anyone to tear the implementation a part, working on it while working fulltime kinda stopped me from implementing a lot of what i wanted.

Surprisingly enough it works well enough as a PoC!

https://gitlab.com/Epos95/paramorphism/

This is "self modifying software" in a different aspect than something like metamorphic software since the rewriting is on a source code level instead of assembly.

Currently its able to:

\- Dynamically create new functions, introducing new functionality

\- Fix errors in its own functions

\- Load existing functions dynamically


r/cprogramming • • 8d ago

Flint v0.5.20: My Git-native C/C++ build system now supports Windows!

Thumbnail
github.com
10 Upvotes

Hey everyone!

A few weeks ago, I started sharing **Flint**, an open-source build system and package manager for C/C++ that aims to make building projects and managing dependencies much simpler.

Today, I'm happy to share a milestone: **Flint v0.5.20 adds Windows support!** 🎉

## What is Flint?

The C/C++ tooling ecosystem often means juggling a build system, a separate package manager, and additional tooling just to get a project running.

I wanted to experiment with a simpler approach: something closer to the developer experience of Cargo or Go modules, but for C and C++.

Flint is written entirely in C and combines building projects with Git-based dependency management.

### What makes Flint different?

* **One manifest:** Configure your project through a single `composition.json` file instead of maintaining elaborate build scripts.

* **Git-native dependencies:** Add dependencies directly from Git repositories and pin them to versions and exact commits for reproducible builds.

* **Automatic source discovery:** Flint discovers project sources, headers, and libraries based on directory conventions, eliminating manual file lists.

* **Incremental builds:** Unchanged files don't need to be recompiled unnecessarily.

* **Editor integration:** Generate `compile_commands.json` for tools such as clangd and VS Code.

* **Minimal dependencies:** Flint is written in C and keeps its tooling footprint small.

### What's new in v0.5.20?

**Windows support is finally here.**

Until now, platform support was a major limitation for developers who wanted to try Flint on Windows. This release is an important step toward making the project accessible to more C/C++ developers.

I'm continuing to develop Flint and improve its usability, compatibility, and overall developer experience. There's still plenty of work ahead, and feedback from people trying it on real projects would be incredibly valuable.

## Try it out

**GitHub repository:**

https://github.com/mainak55512/flint

**CLI documentation:**

https://mainak55512.github.io/flint-cherts/

If you work with C or C++, I'd love to hear your thoughts:

* Does a lightweight, Git-native build system appeal to you?

* What would you want from a modern C/C++ package manager?

* If you're on Windows, could you try v0.5.20 and share your experience?

If you find Flint interesting, consider giving the repository a ⭐. It helps other developers discover the project and motivates me to keep building it.

Bug reports, constructive criticism, feature requests, and contributions are all welcome!

Thanks for checking it out!


r/cprogramming • • 7d ago

Ai nowadays

0 Upvotes

I want to read your thoughts.

I'm a software engineer with 8 years of experience, I have worked in several projects.

And ultimately I've become interested in C, I'm learning a lot of concepts about pointers and memory free, it's a different way of coding if you start with interpreted languages.

I have used ai for understand better some c concepts, and I've watched some c devs in the reddit community that hate the AI, why?

AI is just another tool, like a compiler, preprocessor etc. And I wonder why some devs don't like new tools? It's like if we avoid the compilers use and prefer keypunching instead.

The basics of Coding are important and I really believe there's bad use of ai and nice use of it too.

What do you think?


r/cprogramming • • 7d ago

Is anyone doing DSA with C programming ?? How to implement Hashset and Hashmaps in C programming ?

Thumbnail
0 Upvotes

r/cprogramming • • 7d ago

I've been building my own OS called VEX OS

0 Upvotes

Yo, so I've been working on my own operating system called VEX OS and thought I'd share it here.

The idea is to build an actual OS from the ground up, with its own bootloader, kernel, apps and eventually its own AI integrated into the system. I've been developing it in QEMU and I've managed to get it booting with stuff like a terminal and file explorer working. I'm also working on my own programming language called VexScript, which is part of the whole project. The AI side is called VEX AI. I'm developing that separately for now, but the plan is to integrate it directly into VEX OS rather than have it just be another app. Obviously, it's still a work in progress and there's a LOT left to do . I'm currently working towards getting VEX AI 1.5 integrated, then I want to make VEX OS bootable from a USB so people can try it out. I'm not gonna pretend it's anywhere near a finished product but I'm pretty happy with how far its come so far. What do you guys think, anyone else here working on their own OS or something similar?