r/C_Programming 9h ago

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

23 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 17h ago

Question Meaning of [restrict .n] in manpages?

10 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 16h 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 21h ago

Question Why isn't my code working?

6 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 23h ago

Question How process ids are generated

4 Upvotes

i know fork creates processes but how process ids are generated


r/C_Programming 1d ago

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

39 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

10 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

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

Compressing Lookup Tables

21 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 1d 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

i made lib that beets fmt lib

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

Question Resources to prepare for advanced/trickey questions?

6 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 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

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

8 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 3d ago

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

180 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 3d ago

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

Thumbnail
github.com
25 Upvotes

r/C_Programming 3d ago

Question Can someone explain to me why scanf is unsafe?

66 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 3d ago

559-byte SHA-256 in C

49 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 3d ago

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

13 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?


r/C_Programming 3d ago

Etc random number hack

0 Upvotes
#include <stdio.h>


int main() {
    int s[90];
    printf("%d\n",s[43]);
}

r/C_Programming 4d ago

Project I implemented a modern LLM runtime in 700 lines of C

192 Upvotes

I wanted to understand how modern AI models actually generate text, but most inference codebases are tens or hundreds of thousands of lines long. They’re incredibly impressive, but they’re optimized for flexibility and performance, not for understanding.

So I implemented a complete CPU runtime for Google’s latest open language model, Gemma 4, in about 700 lines of C.

The whole point is that you can open one file, start at main() , and follow a prompt all the way through the program. You can see every buffer that’s allocated, every mathematical operation that transforms the activations, every update to the KV cache, and every step that eventually produces the next token.

I think C is a great language for this kind of project. There’s very little hidden from you. The data structures, memory layout, SIMD kernels, and execution flow are all visible, so the implementation ends up feeling much closer to the hardware than to the diagrams in an ML paper.

https://github.com/ryanssenn/gemma4.c


r/C_Programming 5d ago

One of the coolest features of C: omitted parameter names

90 Upvotes

In all programming languages, there are places where you need to write a function with some parameters that are unused. Mostly to satisfy some callback signature or functional interface. But C makes it easiest of all languages. Where in other languages you have to give the compiler hints like @SuppressWarnings("unused") or name _: String to prevent it from warning you that this parameter here is unused, in C you can just omit the parameter name:

void
foo(int arg, char*) {
    ...implemenation
}

That's it, no hints, no warnings (even with -Wextra), no nuthin'. The compiler understands that if you haven't given this parameter a name, then you intend it to be unused. This is the most concise of all languages and you don't even have to come up with a (useless) name.


r/C_Programming 4d ago

Arbitary Length Numbers Library in C

8 Upvotes

link to code : https://github.com/RamiBrahimi-c/big-ar9am .

hello i am sharing with you project i did this summer , in fact it is a side project was done to be included in another side project which is a crypto lib in C and it is important to say that it is not meant for professional use at all (code : https://github.com/RamiBrahimi-c/cryptography-library ) .

the crypto lib was asked for us to do in a uni class , and due to the fact that i was not able to take my full time with it , like actually doing everything myself from scratch and not vibecode it or use openssl and GMP , so i had to kind of rely on them a little just until the deadline was over and i got marked for it , then i decided to go back to it and make it totally from the ground up .

the crypto lib has :

  • hash functions ( sha256 , sha512 , md4 , md5 )
  • classic ciphers ( affine , cesar , ..etc )
  • symmetric ones ( aes , des , rc4 , blowfish , .. )
  • asymmetric ones that requires arbitary length numbers in protocols like rsa , elgamel , and defil-hellman .

for now all of them except the asymmetric crypto were done from the ground up , i even tried not to copy block of constants if i could calculate it manually ( like the AES s-box that i generated manually by calculating it with galois fields operations in 2⁸ ) , that being said i refused to also rely on GMP to do all the calculations for me too and here where this project was born .

for now it has several features like basic arithmetic operations and even prime numbers testing , generation , finding inverse multiplicative too .. etc you can check my readme ,

yet it is also important that it is not optimized yet , i must note that it will be subjective and based on what i feel like either to go further and see how things like Karatsuba , FFT‑based (Schönhage‑Strassen) , Newton‑Raphson division , ..etc .
although it feels really interesting to see all these mentioned algorithms in action .

an other important point imo is how did i make sure it is at least calculating right , and for that i used Python 3.12.3 , it was extremily helpful and i absolutely appreciate such things like this .

and that would be it , i apologize if i drifted on the main subject i wanted to give the full picture of things , also you can read the README of both of my projects for more details especially the readme of this big num library ( i promise ai just helped with technical details , otherwise it is completely mine )

NOTE : if you want to ask about the why i did what i did , i dont have a clear answer , cuz i love to know how things work and why ? cuz i just want to make my own stuff ? for fun ?
idk , could be one of these could be all of them .

let me know your thoughts ,


r/C_Programming 4d ago

Article I coded in C, and it (me) crashed my laptop

0 Upvotes

Now I have been coding C for a while, so I do know a lot of solutions to specific problems. But to be honest, most of the time I look back at my old code, copy paste, and then re-factor it depending on my current project. I used SHM for my cherries(.)works Pulse project. The reason for that was, Pulse ran on two separate processes; One was the daemon that ran the monitoring in the background, and the renderer, who read the monitored data, and, as the name suggests, rendered it onto the terminal. Because they were two separate processes (which was required, because they both had a while loop), their virtual memory space was not the same, so I had to learn about SHM, however, that was a while ago... So when I started working on Deploy again, and then I needed the same thing again, I was too lazy to look it up again, so I just copied it, pasted it, and moved on.

cherries(.)works Deploy is as you might have guessed a project for deployment. Pretty fun project for me, and very important to manage memory, and processes, especially for this project. I "copied" the architecture for Pulse to Deploy, however the only difference is that Deploy has 3 processes, one is the management process, WITHIN the management process the deployed project is also a separate process. And then the render process. So thats a lot of processes that share a specific chunk of memory. So I not only copied the architecture, but also the SHM method, exactly the way I did in Pulse.

However, I must have forgotten something, I wasnt that sure though, but the crash did happen, everytime I entered a config file that was invalid. I fiddled around with the return values, tried to exit early, and even then, the crash still somehow found its way in. Finally, the smoking gun revealed itself to me.

My own "stop" function, is helpful to me, as it kills the process, and then deletes the file that stored the PID within a folder. While that was running at the end of the main function, within the forked processes, the SHM updated the pids to "-1" if they were invalid. Let me just show you the first line of my stop function;

void stop(pid_t pid)
    kill(pid, SIGKILL);
...

Yeah, I did not know this, but running kill(-1, SIGKILL); in C (or Linux), means; send SIGKILL to every process the caller is permitted to signal, except itself... Well, my laptop did not crash then, I made it crash by either killing every single process, or until an error happened. So yeah, I added a check to see whether or not the pid is a negative number, if it is, I return. Problem was solved.

What that little rodeo taught me, was that C is really not forgiving. Especially, when it does something you told it to. I mean, I did tell it to "kill(-1, SIGKILL)", meaning kill everybody except me (in the computer). I gotta be more careful with the dangerous code that I write...

TLDR; Tried to make my own stop function, did not add a check for negative PIDs. Whole laptop exited....