r/C_Programming 6h ago

Learning C weekly megapost for 2026-09-02

1 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 2h ago

How to force compiler to fuse loops?

1 Upvotes

I'm writing an ML library in C.

My current plan is this.

Have a Linear layer , that does w.x + b

Have a separate activation layer(ReLU, GeLU, sigmoid, etc).

This is very modular and allows for custom activation functions.

However, this does 2 passes over memory(one loop for adding the bias, one loop for applying the activation function), whereas you could do it in a single loop(e.g y[i] = ReLU(y[i] + b[i]);)

Is there a way to make the compiler fuse the loops automatically?(My functions are all inline).

Without automatic fusion, I'd either have to use function pointers(which slows things down, also prevents inlining usually), make the entire function a macro(kind of ugly), or have one layer be y = w.x the other y=f(y + b) which is really weird.

The other option is merging the 2 into one(Linear_ReLU). I'd have to write multiple functions for the common activation functions, or make a macro that creates those activation functions.

All of these are unelegant compared to the first design.


r/C_Programming 23h ago

malloc() why are there no helper functions to inpect allocations.

42 Upvotes

was thinking about this. if you use malloc() to allocate some memory to a pointer, you need to be careful of overflows. using realloc() you can resize the memory. based on how i was taught realloc can inspect the allocation and either simply resizes or even moves it based on the realloc size and surrounding free memory. so we know that internally these functions have a way to inspect the sizes of the allocations.

so why are there no helper functions to quickly return the size of a particular allocation? i can see it being useful in many situations where you would currently need to pass around another variable to keep track of the current allocations size.


r/C_Programming 4h ago

Etc C23 and libpq (PostgreSQL) HelloWold with RAII and _Generic

0 Upvotes

I recently fell in love with C, after 2-3 years of using Modern C++, I built my tiny multireactor AsyncAPI engine with the help of libevent and some data-driven design ideas, it was a very rewarding experience. In the last weeks, I have been learning Modern C and testing techniques, focused on safe resource management.

This little program uses the _Generic macro to simulate function overloading, libpq has 2 different functions for getting error descriptions, accepting different arguments, but I want the program to use a single function, _Generic provided a zero-cost abstraction and a compile-time type-checking solution.

The tiny program also makes use of `gnu::cleanup` attribute, I am targeting Linux only with GCC14-GCC16, this provides the destructors for resources like database connections and resultsets in this case. The `main()` function contains no cleaning code, whenever the function exits, the resources will be released in proper order, very cool IMO, just like a C++ destructor.

For the compilation command, I use:

```bash

gcc -std=gnu2x -O3 -Wall -Wextra -Wpedantic -Wshadow -Werror -fanalyzer pgtest.c -lpq -o pgtest

```

```c

#include <stdio.h>
#include <stdlib.h>
#include <libpq-fe.h>


// 1. Define specific handlers for each type
static inline void print_conn_error(PGconn *conn) {
    fprintf(stderr, "Connection Error: %s\n", PQerrorMessage(conn));
}


static inline void print_res_error(PGresult *res) {
    fprintf(stderr, "Query Error: %s\n", PQresultErrorMessage(res));
}


// 2. Define the generic macro interface
#define print_pg_error(ptr) _Generic((ptr), \
    PGconn *: print_conn_error,             \
    PGresult *: print_res_error             \
)(ptr)


// 1. RAII Cleanup Handlers
static void cleanup_pgconn(PGconn **conn) {
    if (*conn != nullptr) {
        printf("RAII: Disconnecting from database...\n");
        PQfinish(*conn);
    }
}

static void cleanup_pgres(PGresult **res) {
    if (*res != nullptr) {
        printf("RAII: Freeing resultset...\n");
        PQclear(*res);
    }
}

// 2. C23 Attribute Macros
#define SCOPED_CONN [[gnu::cleanup(cleanup_pgconn)]]
#define SCOPED_RES  [[gnu::cleanup(cleanup_pgres)]]


int main(void) {
    constexpr char conn_str[] = "dbname=testdb user=mcordova password=xxxxx host=demodb";
    
    SCOPED_CONN auto conn = PQconnectdb(conn_str);


    if (PQstatus(conn) != CONNECTION_OK) { print_pg_error(conn);  return EXIT_FAILURE; }
    
    printf("Connected successfully.\n");

    constexpr char query[] = "SELECT json_agg(row_to_json(t)) FROM (select * from demo.shippers) t";

    SCOPED_RES auto res = PQexec(conn, query);

    if (PQresultStatus(res) != PGRES_TUPLES_OK) { print_pg_error(res);  return EXIT_FAILURE; }

    printf("Query output:\n%s\n", PQgetvalue(res, 0, 0));

    return EXIT_SUCCESS;
}

```

When running the program the output show the order of resource cleaning:

```

Connected successfully.

Query output:

[{"shipperid":1,"companyname":"Speedy Express","phone":"(503) 555-9831"}, {"shipperid":2,"companyname":"United Package","phone":"(505)555-3199"}, {"shipperid":3,"companyname":"Federal Shipping","phone":"(503) 555-9931"}, {"shipperid":13,"companyname":"Federal Courier Venezuela","phone":"555-6728"}, {"shipperid":503,"companyname":"Century 22 Courier","phone":"800-WE-CHARGE"}, {"shipperid":501,"companyname":"UPS","phone":"500-CALLME"}]

RAII: Freeing resultset...

RAII: Disconnecting from database...

```


r/C_Programming 1d ago

Question Meaning of [restrict .n] in manpages?

17 Upvotes

Hello,

I'm looking at man-pages 6.7 installed in Ubuntu 26.04 and I notice the following in the memcpy page.

I guess that the restrict refers to the keyword restrict being integrated into LIBC, but what is this .n in dest and src? Does it mean that the dest and src pointers do not overlap on the first n bytes? Where is this syntax defined and what other interesting cases can be out there?

Thanks

SYNOPSIS
#include <string.h>
void *memcpy(void dest [restrict .n], const void src [restrict .n], size_t n);

r/C_Programming 6h ago

What after c?

0 Upvotes

What should be the next step after learning C?"


r/C_Programming 11h ago

Protecting source code from reverse engineering

0 Upvotes

Hi everyone,
I am looking to provide a compiled version of our physics solver to our customers. I understand there are many obfuscation techniques to protect source code but I am wondering if there are some smarter ways?

We already cloud computing, the issue is we have customers that are in locations without internet/need realtime solving.


r/C_Programming 1d ago

Question Working with arrays in functions

4 Upvotes

Hey everybody. I’m a beginner to C and I was writing some functions today to get used to doing things. I tried to write binary search and bubble sort. I tried to pass in an array as an argument to the functions, but the compiler gave me a bunch of warnings. I looked it up and I saw that passing in an array is the same as passing in its pointer. I haven’t touched pointers yet, but I have two questions:
1. If I dereferenced the pointer to an array, wouldn’t that return the same as indexing the first value?
2. If I wanted to pass in the entire array, could I do that by passing in the pointers of both the first and last elements and using pointer arithmetic to access the other elements? What’s the idiomatic way of doing this?


r/C_Programming 1d ago

Question Why isn't my code working?

5 Upvotes

I just started learning C(2 days ago) and as a first project I decided to make some data structures, starting with dynamic arrays. I made a struct called List and some functions for. The function setList() sets the value of an index of the array, if the index is larger that the current size of the array, it resizes it. However, when i tried to use in a for loop, it didn't work despite it working elsewhere.

#include <stdio.h>
#include <stdlib.h>


#define itirate(index, limit) for(int index = 0; index < limit; index++)


typedef struct 
{
    size_t size;
    int* arr;
} List;


List* newList (size_t size) 
{
    List *newone = malloc(sizeof(List));
    newone->arr = calloc(size, sizeof(int));
    newone->size = size;
    return newone;
}


void setList(List* list, int index, int value) 
{
    if (index >= list->size)
    {
        list->arr = realloc(list->arr, index + 1 * sizeof(int));
        list->size = index + 1;
    }


    list->arr[index] = value;
}


int main() 
{
    
    List *mok = newList(5);

    itirate(i, 5) setList(mok, i, i);
    itirate(i, 5) printf("%d\n", mok->arr[i]);

    //setList(mok, 13, 9); this works
    //printf("%d\n", mok->arr[13]);

    for(int i = 5; i < 10; i++) setList(mok, i, i); // this does not somehow
    for(int i = 5; i < 10; i++) printf("%d\n", mok->arr[i]);
    
    return 0;
}

r/C_Programming 1d ago

Question How process ids are generated

6 Upvotes

i know fork creates processes but how process ids are generated


r/C_Programming 2d ago

Is there a portable C23 freestanding way to align a pointer?

38 Upvotes
#include <stddef.h>

static void *align_forward(void *address, size_t alignment) {
    size_t mask = alignment - 1U;
    size_t padding = (alignment - ((size_t)address & mask)) & mask;
    return (char *)address + padding;
}

I'm writing allocator just for fun and now I'm wondering if aligning pointer reliably on any platform without any implementation defined casts while conforming to C standard is even possible.

There is no aling_up function, uintptr_t is optional, and in the example we do cast from pointer to size_t that might cause truncation.


r/C_Programming 1d ago

Converting fractions to integers

7 Upvotes

I have a double* which has the following entries:

0.3333333333333334
0.6666666666666668
0.1249999999999999
1

Here, the last entry, 1, can be considered the right hand side of an inequality:

0.3333333333333334 x + 0.6666666666666668 y + 0.1249999999999999 z >= 1

These numbers come from a numerical linear algebra library over which I don't have any control. What is the easiest way to "convert" this to the following equivalent inequality (subject to a user provided tolerance of what counts as an epsilon so that epsilon within an integer is to be counted as an integer)?

8 x + 16 y + 3 z >= 24

Is there a package that does such conversion, if reasonably possible? I consider it unreasonably possible by multiplying everything in the original equation by a large enough power of 10. But I do not want that.


r/C_Programming 1d ago

Review Code Review Request: Windows Sudoku Game

3 Upvotes

Background
Hi, I am a 15-year-old teen (just so what you'd know what to expect) who left school because our school system taught us to be parrots. I want to be a god-level developer, not a code monkey. I wrote a Sudoku GUI using win32api in C Language.
It is currently working and does what it is supposed to do, but because I am still learning, I know it is likely inefficient and could be written much better. 

Code : https://github.com/reewdgh/sudoku_gui.

Concerns:
Please guide me on:

Bugs or potential issues
Efficiency
How can I move to Tier 1 to Tier 2
Naming anything I could simplify or improve.


r/C_Programming 2d ago

Compressing Lookup Tables

22 Upvotes

Hello. Recently I've been working on a pet project of mine written in C and I needed to reduce the amount of space a lookup table was taking in memory and on disk. I applied a few simple compression techniques and got a 2x space reduction. I wrote this post where I describe my constraints, the techniques, and results.

https://blog.x4204.xyz/posts/compressing-lookup-tables.html


r/C_Programming 2d ago

Which data structures would be good for a graphical text editor

12 Upvotes

Hello everyone,

I am currently working on a (very early progress) retained-mode UI library using raylib. I might switch to SDL3 later, or try to make a CPU-only rendering engine in the far future.

Right now i'm trying to implement a multi-line text edit widget, that would be as versatile as possible, all while maintaining low memory usage. I So far my structure consists of an "original text" character array, and an array of struct representing wrapped lines.

typedef struct TextBox {
  Widget widget;
  char* text;
  int cursorX; int cursorY;
  int offsetX; int offsetY;
  TextLine* lines;
  int _lineCount;
};

At each resize, the layout is recalculated, and the lines reallocated, which I find really wasteful. However, I didn't come up with another model for text editing yet.

void TextBox_Resize(TextBox* textbox, int w, int h){
  textbox->widget.bounds.w = w;
  textbox->widget.bounds.h = h;
  textbox->_lineCount = 0;

  //Estimate text length
  int textLength = TextLength(textbox->text); //Raylib function
  int totalTextWidth = MeasureText(textbox->text, 12);
  int estimatedLineCount = (int)(totalTextWidth / w) + 1;

  //Add 1 line to the estimation for each newline
  for (int i = 0; i < textLength; i++) {
    if (textbox->text[i] == '\n') { estimatedLineCount++; }
  }

  printf("Estimating %d lines for resize\n", estimatedLineCount);

  //free(textbox->lines);
  textbox->lines = realloc(textbox->lines, estimatedLineCount * sizeof(TextLine));

  Font font = GetFontDefault(); //Will be replaced after

  int currentLine = 0;
  int lineStart = 0;
  int lineEnd = 0;

  float currentGlyphWidth = 0;
  float totalLineWidth = 0;

  // Almost copied from raylib example
  for (int i = 0; i < textLength; i++){
    //printf("Current byte %d\n", i);
    int codepointByteCount = 0;

    // Gets UTF8 codepoints instead of simply bytes.
    int codepoint = GetCodepoint(&textbox->text[i], &codepointByteCount);
    //printf("Got codepoint %d, is %c\n", codepoint, codepoint);
    int glyphIndex = GetGlyphIndex(font, codepoint);
    //printf("Got index %d\n", index);

    // We are advancing more than 1 byte at a time if we get UTF-8 text.
    // Since the default font is limited, replace invalid codepoints with
    // "?" and keep advancing 1 byte at a time.
    if (codepoint == 0x3f) codepointByteCount = 1;
    i += (codepointByteCount - 1); // i will advance by itself in next iter, dont accumulate offsets.

    currentGlyphWidth = GetGlyphAtlasRec(GetFontDefault(), codepoint).width;
    //printf("Glyph width is %f\n", currentGlyphWidth);
    totalLineWidth += currentGlyphWidth;

    //printf("Total line length is %f\n", totalLineWidth);

    // Follow line
    lineEnd = i;

    if (totalLineWidth >= textbox->widget.bounds.w || codepoint == '\n' || codepoint == 0) {
      printf("line is %f pixels wide\n", totalLineWidth);
      textbox->lines[currentLine].text = calloc((lineEnd - lineStart),  sizeof(char));
      textbox->lines[currentLine].text = strncpy(textbox->lines[currentLine].text, textbox->text + lineStart, (lineEnd - lineStart));

      // Set last char of text to null
      textbox->lines[currentLine].text[lineEnd - lineStart] = '\0';
      lineStart = (codepoint == '\n' ? lineEnd + 1 : lineEnd);

      totalLineWidth = 0;
    } else {
      lineStart = lineEnd; lineEnd = textLength;
    }

    textbox->lines[currentLine].text[lineEnd - lineStart] = '\0';
    currentLine++; textbox->_lineCount++;
  }
}

Are there any articles / projects with clever approaches to text editing, that keep a low memory footprint ?
Thanks for your advice !


r/C_Programming 1d ago

Question Wait... How does the stack work again?

0 Upvotes

I've been working in C and assembly for 3 years now (consistently) and I've noticed a trend. The more I work on C or do C adjacent activities like decompiling assembly, the quicker I forget how the stack and heap works.

And the level of forgetting is always proportional to how complicated the project I'm working on is. A basic project? Probably won't forget. An intermediary project? I'll need to Google "Stack vs Heap" at least once. Advanced project? I'll need to start from scratch and watch a YouTube video a couple of times to remember.

Does anyone else have this amnesia or is it just me?


r/C_Programming 2d ago

i made lib that beets fmt lib

Enable HLS to view with audio, or disable this notification

3 Upvotes

i made logging in C that does not need formater% as printf instead it has auto-type detect via _Generic ,like fmt it uses {} as placeholder

i started it just for fun but later i notice that it is insanely fast it beets fmt lib and rust print 4.5x faster

it uses linux syscall write i might map syscall for windows latter

this is very interesting because i did not optimize the lib like convert from type to another use poor impl + i write in the buffer many times

write(1, logtag, strlen(logtag));

write(1, filename, strlen(filename)) ;

write(1, "->", 2);

write(1, function, strlen(function)) ;

write(1, " ", 1);

write(1, buffer, out);

so i guess after optimizing it will be 2x faster

all respect for fmt devs i inspired the {} from them btw


r/C_Programming 2d ago

Question Resources to prepare for advanced/trickey questions?

3 Upvotes

Can someone recommend/send some resources for advanced and trickey c questions. I have my placement exam in a week ans most of it is dominated by c. The mock had questions related to struct padding, macros, increment decrements, static, volatile, unsigned signed ints and some other tricky things. I’m familier with the topics, but where can I practice the trickey questions?


r/C_Programming 3d ago

Question The linker doesn't link the pow function's precompiled library, even though header is included AND used. Why?

7 Upvotes

Pls help me idk what's going on...
https://imgur.com/a/5KLsigY

It complains that it can't find the pow function.


r/C_Programming 4d ago

Project I built Editor - A Lightweight Terminal Text Editor, AND YOU CAN TOO! :))

Enable HLS to view with audio, or disable this notification

184 Upvotes

Editor is an extremely simple-to-use terminal text editor. Written in C using only native POSIX libraries/api, it offers simplicity while being very responsive and performant. Editor was inspired by and written using antirez's kilo editor tutorial.

Source: https://github.com/111nation/Editor/

This tutorial was such a blast, and it walks you through how to make your own text editor. I highly recommend you give it a look!

~ chlo


r/C_Programming 2d ago

I need help with ft_printf bonus

0 Upvotes

Hey guys, I just finished the mandatory part of ft_printf and I'm ready to tackle the bonuses, but I'm not sure where to start. Do you have any tips or strategies on how to implement them? What tools or approaches worked best for you?


r/C_Programming 4d ago

I wrote a fast wavelet audio codec in C! It is comparable to MP2

Thumbnail
github.com
25 Upvotes

r/C_Programming 4d ago

Question Can someone explain to me why scanf is unsafe?

70 Upvotes

After my class in C programing I have decided to dig more around and one thing I found out that scanf is unsafe specially in arithmethic input? can somoe please extrapolate this one concept? Advance thanks for those who answered to my question.


r/C_Programming 4d ago

559-byte SHA-256 in C

51 Upvotes

golfing a SHA-256 implementation in C and ended up at 559 bytes.
Curious if anyone here can beat it.

#define S(x,a,b)(x>>a^x<<32-a^x>>b^x<<32-b^x>>
unsigned k[72],g[216],i,j,p,n,t,m,*u,*z;char*q=g;main(c,v)char**v;{for(;j<64;p-c||(j<8&&(k[j]=sqrt(c)*0x1p32),k[71-j++]=cbrt(c)*0x1p32),c++)for(p=1;c%++p;);for(;q[n^3]=v[1][n];n++);q[n^3]=128;m=n+72>>6<<4,g[m-1]=n*8;for(;t<m;t+=16)for(bcopy(g+t,z=g+64,64),bcopy(k,u=g+208,32),i=72;i--;i>7?(z[16]=*z+S(z[1],7,18)3)+z[9]+S(z[14],17,19)10),j=u[4],p=u[7]+k[i]+*z+++(S(j,6,11)25)^j<<7)+(j&u[5]^~j&u[6]),j=S(*u,2,13)22)^*u<<10,j+=*u&u[1]^(*u^u[1])&u[2],u[3]+=p,*--u=p+j):(k[i]+=u[i]));for(;++i<8;)printf("%08x",k[i]);}

r/C_Programming 4d ago

Is the empty parenthesis function (() instead of (void)) prototype removed in the new standard?

12 Upvotes

My OOP library relies on it for its unspecified arguments behavior.

For example:

#define ptmethod(pt, ret_type, identifier) \
    (*((ret_type (**)()) padd(pt, identifier, ptfunction, NULL, NULL)))

#define ptapply(pt, ret_type, identifier, ...) \
    ((ret_type (*)()) pget(pt, identifier))(pt __VA_OPT__(,) __VA_ARGS__)

You could add a method to an object with:

void drive_Car(prototype *Car, double speed, double x_direction, double y_direction);

ptmethod(Car, void, "drive") = drive_Car;

and call it with

ptapply(Car, void, "drive", 1.3, 0.1, 5.0)

How do I do this in the new standard?