r/C_Programming • • Feb 23 '24

Latest working draft N3220

131 Upvotes

https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf

Update y'all's bookmarks if you're still referring to N3096!

C23 is done, and there are no more public drafts: it will only be available for purchase. However, although this is teeeeechnically therefore a draft of whatever the next Standard C2Y ends up being, this "draft" contains no changes from C23 except to remove the 2023 branding and add a bullet at the beginning about all the C2Y content that ... doesn't exist yet.

Since over 500 edits (some small, many large, some quite sweeping) were applied to C23 after the final draft N3096 was released, this is in practice as close as you will get to a free edition of C23.

So this one is the number for the community to remember, and the de-facto successor to old beloved N1570.

Happy coding! 💜


r/C_Programming • • 2d ago

Learning C weekly megapost for 2026-10-14

5 Upvotes

If you have questions about how to learn C:

  • which books are best?
  • which videos are best?
  • which classes are best?
  • which websites are best?
  • is there a "roadmap"?
  • what projects can I do?

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

Question is doing ~INT_MAX undefined behavior?

38 Upvotes

basically the title, i think producing INT_MIN by doing 1 << 31 is UB, so i thought of doing ~INT_MAX, but i am not sure if it's UB. sorry if it's dumb.


r/C_Programming • • 4h ago

Question Can code injection be countered by randomizing the base address of the stack?

0 Upvotes

In your answer include a description of the assumption you have made about the binary code and memory layout of the program. Explain if it can be countered by randomizing the base address of the stack.

a) Explain a mechanism that can be used by the attacker to force the program to execute arbitrary code.

1 void printInput(char *input) {
2   char buffer[50];
3   char secret[20] = "Pwd123456";
4   if (strcmp(input, secret) == 0)
5     print(secret);
6   else
7     printf(input);
8     strcpy(buffer, input);
9 }
10 int main(int argc, char *argv[]) {
11   if (argc != 2) {
12     return 1;
13   }
14   printInput(argv[1]);
15   return 0;
16   }

What I don't understand:
The solution says that it can be countered by ASLR because we need the address of the buffer. I sort of understand that we need to inject our code somewhere in the buffer thus if we want to overwrite the return address to point to the beginning of the buffer, where our code is, we need to know the address? Although I wonder do we really need the address? Can we not use offset?

Either way the solution seems to suggest that we should overwrite the return address and put the code immediately after and set the return address to point right after it. So I am not at all sure what they mean. Can someone explain to me why ALSR works here? I'd appracite it.

Solution in the answer sheet:
If the input contains 50 bytes, then <address of return pointer + 8>, then binary code, strcpy at line 9 over- flows the stack variables and overwrites the return pointer with the address immediately after the return pointer. After the return pointer, the overflow additionally writes the bi- nary code. Therefore, when the function| returns it jumps to the address above the return pointer on the stack. This attack can be countered by base stack randomization, since it prevents the attacker from knowing the address of buffer and therefore the address where the binary code has been injected. This makes not possible to know the value that should be written in the return pointer.


r/C_Programming • • 17h ago

Question Is this Linux project worth building, or should I try something else?

0 Upvotes

Hey! I'm a second-year CS student looking to build a serious side project to improve my skills and have something worth showing on GitHub.

I'm considering making a Linux tool in C that tracks processes and lets you visually compare different runs of a program (forks, execution times, crashes, etc.).

I'm not sure how useful or original this would be, though.

Do you think it's worth building? Or would you suggest a different project that could be more interesting or useful?

I'm open to completely different ideas. I'd appreciate some honest feedback before spending months on something!


r/C_Programming • • 1d ago

Question Why not specifying what to include ?

11 Upvotes

Hi, sorry if there is English mistake, it's not my first language.

I found online that the #include is replaced by preprocessor by the whole file being included, and I wondered why C isn't made so we can specify only parts of the files to include (like `import { x, y, z } from "file"` in typescript) so the compiled file is lighter ?


r/C_Programming • • 1d ago

USACO Beads Problem: why does nothing show in the output file?

0 Upvotes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXN 701

int main(){
    FILE* fin = fopen("beads.in", "r");
    FILE* fout = fopen("beads.out", "w");

    int length, N, largest = 0;
    int current;
    char rightletter, leftletter;

    fscanf(fin, "%d", &N);
    char sequence[MAXN];

    fscanf(fin, "%s", sequence);
    strcat(sequence, sequence);

    for(int i = N/2; i < N + (N/2); i++){
        current = i;
        length = 0;

        // RIGHT

        while(current < 2 * N && sequence[current] == 'w' && length < N){
            current++;
            length++;
        }

        if(current < 2 * N && length < N){
            rightletter = sequence[current];
        }

        while(current < 2 * N && (sequence[current] == rightletter || sequence[current] == 'w') && length < N){
            length++;
            current++;
        }

        // LEFT

        current = i - 1;

        while(current >= 0 && sequence[current] == 'w' && length < N){
            current--;
            length++;
        }

        if(current >= 0 && length < N){
            leftletter = sequence[current];

        }

        while(current >= 0 && (sequence[current] == leftletter || sequence[current] == 'w') && length < N){
            length++;
            current--;

        }

        if(length > N) {
            length = N;
        }

        if(length > largest) {
            largest = length;
        }

    }

    fprintf(fout, "%d\n", largest);
    return 0;

}

My code should work. Idk why nothing is being output in the output file.


r/C_Programming • • 1d ago

Project My C project Pulse grew better than expected

0 Upvotes

A while back I started working on my project cherries(.)works Pulse. A simple Linux monitoring system, coded in C, and focused on performance, resource usage and persistence. Now a when I started this project I had no knowledge of C, and kinda learned along the way, but now around 2-3 months have passed, and I am surprised with how far it has come.

Personally, I never had anyone commit to my FOSS projects before. Didnt expect anything different this time tbh, as I was programming the whole thing in C. Created numerous issues, as I wanted THIS FOSS project to be more different and professional than the others.

A month or two after the release, I go on GitHub to look at my issues via my phone, and see a PR solving one of the issues. It was surreal seeing C code not by me, now being written FOR me. Ofc i had to read through it carefully to make sure nothing eas wrong with it, but once I merged it, it felt beautiful.

People have implemented;
- Pretty printing the config file
- Improving type annotations
- Adding JSON output for commands
- Displaying hostname on website
- Counting process amount

and numerous more.

Pulse was just a small C project of mine that quickly spiraled into something bigger. I plan on adding new good first issues soon, as there is STILL a lot of work to do. If there are any C programmers interested in contributing, or giving feedback, feel free to do so. would be very glad.

https://github.com/cherries-works/pulse


r/C_Programming • • 2d ago

Question Has anyone used the libqt6c library? If so, what kind of results did you get, and how does it compare to Gtk?

10 Upvotes

I recently came across a Qt binding library for C, but I haven't seen any discussion about it on Reddit. If anyone here has used this library, I’d be curious to know what it’s like in terms of usability—especially since C, as we know, lacks many of the features found in C++.

https://github.com/rcalixte/libqt6c


r/C_Programming • • 1d ago

78K Weekly visitors

0 Upvotes

Are people starting to drop AI.. or ?


r/C_Programming • • 1d ago

Project Announcing scaffold 0.1.0

0 Upvotes

Hi,

This is scaffold, a flexible data and "rpc-like" code generator for C using YAML as description.

After years of protobuf (with nanopb), I've decided to get rid of it to create my own templating system.

I won't go in details why we have decided to get rid of nanopb but in short: we were having hard times about some of the limited features like deep-cloning, too limited enum support and a slow encoding process.

Plus, we wanted to add flexibility with a custom YAML document that could be parsed using a tool to produce on-demand different kind of functions. For example, we wanted that some types could be converted to JSON, some to be inserted into a SQLite database. As such, having a unique YAML document that could be used for different purposes led us to write this software.

The scaffold tool is written in C, because, we write in C and don't want additional dependencies :). It reads a YAML document and creates an intermediate AST with updated fields to get more information. Then, it processes it into a templating system with basic scripting constructs including for, if, substitution with filters.

Example of a minimal object:

# types.yaml
objects:
  - name: point
    comment: This is an awesome point.
    fields:
      x: uint32
      y: uint32

Generate functions for this object using:

scaffold emit h types.yaml > types.h
scaffold emit c types.yaml > types.c

The generated code by the built-in templates include comments that can be split on multiline providing good LSP support with Doxygen format.

/**
 * \struct point
 *
 * This is an awesome point.
 */
struct point {
    /**
     * Field 'x' of type uint32.
     */
    uint32_t x;

    /**
     * Field 'y' of type uint32.
     */
    uint32_t y;
};

The template system is flexible enough to write extra custom code while iterating the object fields using {{for}} loops.

{{for obj in objects}}
  {{for field in obj.value.fields}}
    // here field will be uppercased with the :U filter :)
    printf("Serializing the {{field.key:U}} field\n");
  {{endfor}}
{{endfor}}

Finally, because we wanted our custom RPC API, the scaffold project provides support for request/reply and events widely inspired by wayland-scanner.

Declaring function feels like natural:

serialization: true
functions:
  - name: hello
    comment: Say hello to my friend!
    args:
      name: string

On the "client" side, a function is generated in the form:

int64_t hello(struct hello_args *args, void *ctx);

On the "implementation" side, a function pointer is provided in a handler struct:

/**
 * \struct handler
 * \brief Functions table handlers.
 */
struct handler {
    /**
     * Handler for function 'hello'.
     */
    int (*hello)(struct hello_args *args, struct hello_value *value, void *ctx);
};

And the implementation side can call the auto generated dispatch function that will decode the incoming requests to call the appropriate functions.

int
dispatch(
    const struct handler *handler,
    const struct listener *listener,
    int64_t *nread,
    int64_t *nwritten,
    void *ctx
);

How does it work? The generated function relies on two unique external linkage that the user has to provide:

  • int64_t sc_read(void *ctx, void *data, uint64_t amount)
  • int64_t sc_write(void *ctx, const void *data, uint64_t amount)

Thus, calling dispatch will attempt to decode a request using successive calls to sc_read, call the appropriate function pointer into the handler structure and then will try to encode using successive call to sc_write. Nothing more.

Note: this project is heavily being tested and already used in production but few bugs may persist and feel free to contribute.

Future plans and never plans:

  • Yes: better bitmask enumeration support.
  • Yes: more portability on non-POSIX platforms.
  • No: automatic default values.
  • No: union or protobuf oneof kind.

Links:

Like every source code I write, this project has a perpetual anti degenerative-AI policy.


r/C_Programming • • 1d ago

Is this a VS Code newline/paste input bug?

1 Upvotes

I wrote the following C program in VS Code. Its purpose is to find words that appear in both of two English paragraphs.

(Details: a word must contain at least four letters; each paragraph ends with a \n; the output words should be sorted in ascending order.)

To keep track of how far the program has gotten, I deliberately print stage1 / stage2 after each of the two paragraphs has been read.

But when I run it in the terminal, this is what happens.

First I copy two paragraphs of English text, for example:

In computer science, artificial intelligence (AI), sometimes called machine intelligence, is intelligence demonstrated by machines, in contrast to the natural intelligence displayed by humans and animals. Colloquially, the term "artificial intelligence" is used to describe machines that mimic "cognitive" functions that humans associate with other human minds, such as "learning" and "problem solving". From Wiki. Machine learning is a way to achieve artificial intelligence.

I assumed that after pasting, pressing Enter right after intelligence. would produce stage1, and that stage2 would follow right away, printing the words. But in reality I get nothing but a cold, lonely stage1. Pressing Enter again does absolutely nothing. I type a random letter, press Enter once more — and only then do stage2 and the rest of the output finally appear.

I'm a first-year CS student and still not very familiar with programming. I'd like to know: is this a VS Code problem, or is it my problem?

#include <stdio.h>

#include <string.h>

void clean(char (*word)[21], int len) {

for (int i = 0; i <= (len); i++) {

if ((*word)[i] >= 'A' && (*word)[i] <= 'Z') {

(*word)[i] -= 'A' - 'a';

}

}

}

void print(char (*words)[1000][21], int m) {

char temp[21];

char min[21];

int flag = 0;

strcpy(min, "z");

strcpy(temp, "z");

for (int j = 0; j <= m; j++) {

strcpy(min, "z");

for (int i = 0; i <= m; i++) {

if ((strcmp(min, (*words)[i]) >= 0) &&

(strcmp(temp, (*words)[i]) < 0 || flag == 0) &&

((*words)[i] != 0)) {

strcpy(min, (*words)[i]);

}

}

flag = 1;

strcpy(temp, min);

printf("%s\n", min);

}

}

int main(void) {

int r;

char shit[2];

int len1;

int len2;

char para1[1000][21] = {{0}};

char para2[1000][21] = {{0}};

char space;

char answer[1000][21] = {{0}};

for (int i = 0; i < 1000; i++) {

scanf("%[A-Za-z]", &para1[i][0]);

len1 = i;

scanf("%*[^\nA-Za-z]");

if ((r = scanf("%[\n]", shit)) == 1 || r == EOF) {

printf("stage1\n");

break;

}

}

for (int j = 0; j < 1000; j++) {

scanf("%[A-Za-z]", &para2[j][0]);

len2 = j;

scanf("%*[^\nA-Za-z]");

if ((r = scanf("%[\n]", shit)) == 1 || r == EOF) {

printf("stage2\n");

break;

}

}

for (int i = 0; i <= len1; i++) {

clean(&(para1[i]), strlen(para1[i]) - 1);

}

for (int j = 0; j <= len2; j++) {

clean(&(para2[j]), strlen(para2[j]) - 1);

}

int m = 0;

int flag = 0;

for (int i = 0; i < 1000; i++) {

for (int j = 0; j < 1000; j++) {

if ((strcmp(para1[i], para2[j]) == 0) && (strlen(para1[i]) >= 4)) {

for (int p = 0; p < m; p++) {

if (strcmp(para1[i], answer[p]) == 0) {

flag = 1;

}

}

if (flag == 0) {

strcpy(answer[m++], para1[i]);

}

flag = 0;

}

}

}

m--;

print(&answer, m);

}


r/C_Programming • • 2d ago

Question Why are assignment expressions lvalues?

12 Upvotes

I was reading up about lvalues and understand them now as something that resolves to an address(memory location) in the program. So a variable x is an lvalue (because it is mapped to some address on the stack) and similarly *x , x[i], strings are all lvalues. But if this is the case why is an expression a = b , not an lvalue? Here the expression would assign b to a and then return a as evident in assignments like so: int c = a = b. (I know that the equals sign is right associative and hence this would get resolved as c = (a = b), but that doesn't really invalidate the fact that a = b resolves to an address in the program?)


r/C_Programming • • 4d ago

Article A modern web app in C

Thumbnail prophitt.me
206 Upvotes

r/C_Programming • • 2d ago

Question What is C

0 Upvotes

Hey I'm a cybersecurity student just started 2 months ago

Just wanted to understand what C is as a language why is it so fast compared to other languages like py etc..

Chatgpt and yt videos didn't help me to understand :

  1. Does c talk to the hardware directly or through a compiler like other languages if yes why is it faster then ?

  2. I heard something like : c makes code that puts things in a CPU in a specific places not randomly like other languages I'm sorry I don't remember exactly ik it's confusing

  3. Do you need c for cybersecurity in the red team field

Thank you guys so much can't thank you enough for helping hope I make sense asking questions like these


r/C_Programming • • 3d ago

Project Started learning C and would like to get some feedback

Thumbnail
codeberg.org
15 Upvotes

This is my first C program, other than "hello world". I like how it turned out, but there probably is a way to make it cleaner. The screensaver itself is just a demo for screenbuffer library. Would be happy to get some reviews.

No AI used.

Thanks.

Repo link: https://codeberg.org/pinkcucumber/screensaver.git

Compiling: gcc framebuffer.c screensaver_circles.c -lm -o screensaver

Sorry for bad english, it is not my main language


r/C_Programming • • 3d ago

[Request] Looking for a summary, notes, or cheat sheet on Static vs. Dynamic Lists in C

0 Upvotes

Hiiii

I'm currently studying data structures in C and I'm trying to solidify my understanding of static lists (arrays) versus dynamic lists (like dynamic arrays and linked lists).

Any resources, GitHub links, or personal notes you'd be willing to share would be hugely appreciated. Thanks in advance!


r/C_Programming • • 4d ago

Article Arena Allocators in C

Thumbnail eliasebner.com
53 Upvotes

I recently started implementing arenas in my programming and I thought that some beginners could very much benefit from this info. I wrote an article about it. For those that are unaware, arenas allow to greatly simplify the burden of managing memory manually in C. I hope it helps, tell me what you think!


r/C_Programming • • 2d ago

Question Beginner in C — need help compiling my program on Windows.

0 Upvotes
#include <stdio.h>


int main(void) {
    int opcao;


    do {
        printf("\n=======================\n");
        printf(" TECNFIX INFORMATICA\n");
        printf("=======================\n");
        printf(" 1 - Cadastrar Cliente\n");
        printf(" 2 - Cadastrar equipamentos\n");
        printf(" 3 - abrir Ordem de Serviço\n");
        printf(" 4 - Consultar Ordem de Serviço\n");
        printf(" 5 - Sair\n");
        printf("===============================\n");
        printf("Escolha uma opcao:");


        scanf("%d", &opcao);


        switch (opcao) {
            case 1:
                printf("Cadastro Clientes selecionados!\n");
                break;
            case 2:
                printf("Cadastro de equipamentos selecionados!\n");
                break;
            case 3:
                printf("abrir Ordem de Serviço!\n");
                break;
            case 4:
                printf("Consultar Ordens de Serviço selecionado!\n");
                break;
            case 5:
                printf("Encerrando o sistema TechFix...\n");
                break;
            default:
                printf("Opcao invalida!. Tente novamente.\n");
        }



    } while (opcao != 5);


    return 0;
}

r/C_Programming • • 3d ago

Why not preprocess in C itself?

0 Upvotes

For example, at the beginning of the code, have something like this:

replace_token("foo", "\"hello\"");
use_defer();

#define PREPROCESSOR_END

#include <stdio.h>
void main() {
  defer(printf(" world\n"));
  printf(foo);
}

Then before compiling, a script simply runs the upper part, with the lower as a global string. The difficulty of course is in implementing the functions. But this way you don't have to wait for a C feature to be added in 2030. Which now that I think of it isn't that far off. Time flies. Perhaps there are better uses of it than programming, like dancing at party and doing the sex.

Edit: I mean like this:

preprocess ./main.c -o new_main.c; gcc new_main.c

It happens before anything else and only affects one file.


r/C_Programming • • 4d ago

Etc An small example of __attribute__(cleanup)'s power: a context manager.

10 Upvotes

Forgive the typo :) Here's something that will allows you to never unlock a mutex manually again:

#define with_lock0(uniq, mutex) \
    typedef struct { pthread_mutex_t *mtx; bool hold; } __lock##uniq; \
    void __cleanup_##uniq(__lock##uniq *lock) { pthread_mutex_unlock(lock->mtx); } \
    for(__lock##uniq _lock __attribute__((cleanup(__cleanup_##uniq))) \
        = { (pthread_mutex_lock(mutex), (mutex)), true }; \
        _lock.hold; \
        _lock.hold = false)

#define with_lock(mutex) with_lock0(__COUNTER__, mutex)

void do_very_important_business(void) {
    with_lock(&g_mutex) {
        // transfer BIG money
    }
 }

If you check it out on Godbolt you'll see it has 0% overhead. Of course this pattern is usable for many different objects.


r/C_Programming • • 3d ago

Question Difficulties with MinHook

3 Upvotes

Hi there, so I’ve been trying to patch out a piece of code in The Sims Legacy Collection that disables the -debug_objects command line from being enabled, but both MinHook and CMake are giving me such a hard time that idk what else to do or where to ask… There are no tutorials AT ALL for compiling MinHook with MinGW-W64-gcc, only for Visual Studio (not Code!) which I can’t use because I’m on Arch Linux…

If anyone could advise me please I’d really appreciate it…


r/C_Programming • • 3d ago

I built an AArch64 bootloader from scratch in C and Assembly

0 Upvotes

Decided to build an AArch64 bootloader from scratch in C for QEMU virt It handles device tree handoff, VirtIO storage, EXT4/FAT, and verified A/B boot with Ed25519

Code: https://github.com/rdrunky/bootloader

Any feedback on the C code or driver structure is appreciated :D


r/C_Programming • • 5d ago

Project Compile C/C++ into assembly and emulate it in the web in many architectures

280 Upvotes

Hello everyone! For the past few years I've been working on ASM editor (github), an IDE for assembly running completely on the web with many architectures available (x86, mips, risc-v, m68k, z80 and more to come) with a lot of debugging features like step by step execution, undo, memory and registers viewers, breakpoints, observability of what each instruction did and much more!

Recently I've added a feature I had dreamed of adding for a long time, C and C++ compilation! It allows you to write C and C++ code (with a subset of libc available), compile it to assembly to see how each line was compiled, to then execute it with all the debugging tools available in the IDE.

I'd love to get opinions/suggestions/feedback about it, please let me know in the comments!

Here is an example of fibonacci in C compiled to x86

I've been working on this app for around 3 years, initially as a replacement for easy68k and the MARS simulators so that my university could use a more modern alternative, to then add x86 and risc-v.
Recently while using AI i refactored other emulators to add the tools needed for the interfaces used inside the app and i managed to add z80 and hopefully arm and more architectures soon.


r/C_Programming • • 5d ago

Question Using 1<<N "just for data size"

13 Upvotes

Hi, I was reading through some code and found something interesting.

Personally, I usually do this when I need to specify an array length (or declare a size):

#define MAXLEN 4096

but when I read some styles there are some lines like this.

/* max length is 2^12; little endian */
#define MAXLEN (1<<12)

If bitwise operations aren't actually involved, I'm not really sure why some programmers write 1<<N just to represent 2N. Although it definitely make sense in low-level programming (or memory-constrained environments), I don't see any real advantage to using 1<<N when resource is plenty. It's harder to read, and programmers like me even need a calculator just to figure out the decimal value.

How do you think about using 1<<N when it's not strictly required? Is it just a matter of coding style?

P.S) Sorry for poor English.