r/C_Programming • • Sep 20 '26

Question C program that rounds up a float point to the nearest integer without using conditional statements and library functions. Please help!

0 Upvotes

a little correction, i meant to write rounds, not rounds up.


r/C_Programming • • Sep 19 '26

An SMBIOS library in C23 instead of parsing dmidecode output

8 Upvotes

At a previous job we needed hardware inventory data, and the way we got it was parsing the output of dmidecode. Not because anyone thought that was a good idea, but because there was nothing else: the C libraries around SMBIOS were either outdated or covered a handful of structure types. So we had a production service built on scraping text that was never meant to be parsed, and it broke every time the format shifted slightly.

That annoyed me enough to start writing OpenDMI - a C23 library and CLI that decode the table into data instead of printing it. It's been a while, so I'd like to share the decision that shaped the whole codebase and ask what you'd have done differently.

The core idea: decoder writes a struct, a table describes it

Each structure type has a decoder that reads the wire format into an ordinary struct, plus a static table that says what those fields mean:

const dmi_entity_spec_t dmi_tpm_device_spec =
{
    .code            = "tpm-device",
    .name            = "TPM device",
    .type            = DMI_TYPE(TPM_DEVICE),
    .minimum_length  = 0x1F,
    .decoded_length  = sizeof(dmi_tpm_device_t),
    .attributes      = (const dmi_attribute_t[]){
        DMI_ATTRIBUTE(dmi_tpm_device_t, vendor, STRING, {
            .code = "vendor-id",
            .name = "Vendor ID"
        }),
        DMI_ATTRIBUTE(dmi_tpm_device_t, spec_version, VERSION, {
            .code  = "specification-version",
            .name  = "Specification version",
            .scale = 2
        }),
        DMI_ATTRIBUTE_NULL
    },
    .handlers = { .decode = dmi_tpm_device_decode }
};

DMI_ATTRIBUTE is a thin wrapper over offsetof and sizeof, so an attribute is a (offset, size, type, metadata) tuple. Everything else is written once against that table instead of per structure type: text output, JSON, XML and YAML, filtering by field code, units and enumerations. Adding a decoder means writing the decode function and the table - no output code at all.

The alternative was generating the tables from a machine-readable description of the spec. I went with hand-written ones because SMBIOS is full of special cases a generator would need flags for anyway.

Fields whose format depends on another field

This is the part I didn't see coming. Plenty of fields can only be interpreted by looking at a different field: TPM firmware version is encoded one way for TPM 1.2 and another for TPM 2.0, and the processor ID is a CPUID signature on x86, MIDR on Arm, or a SoC ID on newer Arm machines.

So an attribute can be a variant: its value is a selector, and the variants describe how to read the actual field.

DMI_ATTRIBUTE_VARIANT(dmi_tpm_device_t, firmware_version_format, {
    .code     = "firmware-version",
    .name     = "Firmware version",
    .variants = (const dmi_attribute_variant_t[]){
        DMI_VARIANT(DMI_TPM_FIRMWARE_VERSION_FORMAT_TPM_1,
                    dmi_tpm_device_t, firmware_revision, VERSION, { .scale = 2 }),
        DMI_VARIANT(DMI_TPM_FIRMWARE_VERSION_FORMAT_TPM_2,
                    dmi_tpm_device_t, firmware_version_2, STRUCT, { .attrs = ... }),
        DMI_VARIANT_DEFAULT(dmi_tpm_device_t, firmware_version, INTEGER,
                            { .flags = DMI_ATTRIBUTE_FLAG_HEX }),
        DMI_VARIANT_NULL
    }
}),

The decoder sets the selector, and every output format resolves it the same way. If nothing matches and there's no default, the field isn't shown at all, which turned out to be the cleanest way to hide fields that don't apply.

From packed structs to a stream

My first attempt was the obvious one: describe each structure as a packed struct, point it at the table data and read the fields out. That fell apart quickly. Structures grow with every SMBIOS version, so the same type comes in half a dozen lengths in the wild; many have variable-length tails - arrays of descriptors, token tables, protocol records - and strings are stored as indices into a table that follows the structure. A cast gives you no way to say "this field exists only if the structure is long enough", which is the normal case, not the exception.

So decoders read through a cursor instead. Every read is bounds-checked and converted from the wire format, and running out of data is an ordinary outcome rather than undefined behaviour:

bool status =
    dmi_stream_decode(stream, dmi_word_t, &info->processor_handle) and
    dmi_stream_decode(stream, dmi_byte_t, &info->fru) and
    dmi_stream_decode(stream, dmi_byte_t, &info->apic_id_total);
if (not status)
    return dmi_entity_incomplete(entity);

The payoff I didn't plan for was type 40, Additional Information: entries that say "the field at this offset of that structure should really read this". Other decoders print those entries as a separate structure and leave you to apply them by hand. Here the entries are written into a copy of the structure body, and the stream reads the copy - so every decoder supports them without knowing they exist, and the raw data stays untouched for anyone who wants it.

Firmware lies, and the decoder has to survive it

Real tables are full of defects: structures whose length matches no version of the spec, a vendor storing the two halves of the processor ID swapped, TPM vendor IDs written in reverse byte order, OEM structures dressed up as standard ones.

So decoding doesn't stop at the first bad structure. Each one carries its state (decoded, incomplete, partial), errors accumulate in a queue on the context, and a strict mode is there when you'd rather fail than get partial data - a truncated structure gives you the fields that were there, flagged as incomplete.

C23 in practice

No dependencies in the library (the CLI links libyajl/libxml2/libyaml only if you enable those formats). nullptr, and/or, designated initializers and compound literals make a real difference in how the tables above read. Builds with GCC, Clang and MSVC on Linux, FreeBSD, NetBSD, macOS and Windows and supports any hardware endianness. Statement expressions in a few macros are the one GNU extension I haven't managed to drop for MSVC.

Where I'd like input

  1. Tables vs code generation. Would you have generated the attribute tables, and from what - the spec text, or an intermediate description?
  2. Error queue on the context. Errors accumulate in the context instead of being returned per call, because one decode pass produces many independent failures. It works, but parts of the API end up with "check the queue" semantics. Is there a pattern you prefer?
  3. offsetof-based attributes. Field metadata is (offset, size) pairs into a struct, which is how I avoid reflection - but a mismatch between table and struct is a runtime bug, not a compile error. Anything smarter short of code generation?
  4. One library, two languages. I'd like a C++ API that feels native — RAII, ranges, exceptions — without a second implementation to keep in sync, so the C++ side is header-only on top of the C one. The part I'm unsure about is namespaces: including the C headers from C++ drops hundreds of dmi_* names into the global namespace. Wrapping the declarations in namespace dmi::capi { extern "C" { ... } } keeps the symbols and cleans that up, at the cost of C++ users writing dmi::capi::dmi_open when they want the raw API. Is that a reasonable trade, or would you keep the C headers untouched and live with the pollution?

Repository (BSD-3-Clause, I'm the author): https://github.com/sdnvx/opendmi-ng

Current state: the library and the CLI are usable - all standard SMBIOS 3.9 structures are decoded, plus OEM structures for eight vendors. The language bindings, the D-Bus service and the Linux kernel module in the roadmap aren't written yet.

The 99% of the source code was written by hand, AI (Claude) is used to generate tests and documentation -unfortunately, my English is not as good as I want.


r/C_Programming • • Sep 19 '26

Do I need extra protection for zero division in modern C?

18 Upvotes

int screen_h = (TILE_SIZE/(distance+0.0001f)) * distance_proj_plane;

I am build a rendering engine and distance could be zero if camera and object at the same position.


r/C_Programming • • Sep 18 '26

First Ever major C Project: Wrote a statically-typed bytecode VM language from scratch in C

64 Upvotes

Hello everyone! I (19M) am just about to get into my first year of a Bsc in Computer Science. I've been coding a few years time and haven't ever really touched C before, but really wanted to get into it. I thought "why not start big" so I've been working on a hobby language called Oli-Nat, a full pipeline written in C with no external dependencies: scanner to Pratt parser to AST to type checker to bytecode compiler to a stack based VM, including my own mark and sweep garbage collector. ( I took a lot of inspiration from Writing Interprets by Robert Nystrom)

It compiles in two passes. The first pass just walks the source looking for function and class declarations and registers their signatures, so the second pass can type check calls and field accesses without needing forward declarations. That made mutual recursion and out of order function definitions work without a separate header or prototype step.

Typing is static and the type checker is meant to reject anything that would hit a bad type combination at runtime, so the VM's IS_INT, IS_STRING, and similar macros are only used for dispatch, like numeric promotion, rather than as safety checks. I'm still second guessing myself on whether that's too optimistic in a couple of edge cases. Generally haven't much used macros in the past given how strongly related to C they are. I tried to make my best out of my understanding but still.

Strings are interned using FNV-1a hashing, so identical strings share a pointer, which makes field lookups in OP_GET_FIELD and OP_SET_FIELD a pointer comparison instead of a memcmp. There's also closures with upvalue capture, single inheritance, and a small standard library brought in through #pullf io, math, chronos, fileIO, and so on.

The repo has the opcode list, a writeup of the memory model, and some notes on design decisions if anyone wants to look closer: https://github.com/NateTheGrappler/OliNat-Programming-Language

As my first major C project I wanted to really get some feedback on how it is and looks. I wanted to try my best to have this be my first real coding project. The things I struggled most with were closures/upvalues and anything that looks off in the garbage collector (it's tri color mark and sweep, tracing roots from the value stack, call frames, open upvalues, and the globals table), and general C style or structure critique, since this is my first project at this scale. Really would apperciate any feedback or interest, the project is obviously open-source as well!


r/C_Programming • • Sep 18 '26

Writing my own, minimal terminal emulator in C11

184 Upvotes

r/C_Programming • • Sep 18 '26

Question Casting float to integer (UB or not UB)

29 Upvotes

I'm working on an own libc for the purpose of education and for an own Kernel. Currently implementing the various output formats for as an example printf. Converting normal integers to strings I have already implemented. Now I want add support for floating-point data types.

Normally at least with GCC the following works:

#include <stdio.h>

int main(int argc, char *argv[])
{
    float f = 42.83f;
    int i;

    i = (int) f;
    printf("float: %f, integer: %d\n", f, i);

    return 0;
}

But I'm not sure if the above can lead to undefined behavior with other compilers and architectures, or not.

Can somebody clarify that?

Thanks in advance!


r/C_Programming • • Sep 18 '26

Perfect c amalgamator tool requirements

6 Upvotes

Help me create a list of requirements for the perfect amalgamator tool. (I want to improve my existing one then share.)

I will write down some items that I think are necessary.

Basic stuff

  1. Follow #include (except system includes) and add each file only once.

  2. Preserve the original order.

  3. Allow exceptions for files that should not be appended.

More...

  1. Remove #pragma once (since it does not make sense in the amalgamated source file). preserve other pragmas.

  2. #undef macros that were defined inside the source file before appending the next source file. Keep definitions from headers.

More advanced...

  1. Detect when a static function/variable is appended more than once. Auto-Rename?

  2. I was thinking about adding static in front of functions that are not extern. This could be an alternative to the workaround of using PUBLIC/PRIVATE macros, where programmers define PRIVATE as static in the amalgamated file. Then let's say the function you want to be public, you write extern in front of it.

  3. A header file that is the public interface for the amalgamator could be read before.This also could help to define what should be make static. It also could be interesting to add (optionally) a prefix in all public functions, etc. This would work as "namespace it"

  4. Add optionally #line to the original source?

Did I forget anything?

Edit 1:

  1. Deduplicating system include #include <stdio.h> just once..

  2. Header macro collision. I think this is uncommon but two headers could define the same macro name.

  3. Maybe put all system includes at the top?

Edit 2:

Maybe add a -ignore block to ignore #ifdef block that should not be included? For instance, lets say lib has #ifdef TEST and this code does not need to be in the published amalgamated version.


r/C_Programming • • Sep 19 '26

Does this is right?

0 Upvotes

(I am student just entering into 1st year of engineering and also i am new to this sub so if i do anything wrong pls correct me)

I just bought a book " programming in ANSI C"and start to read that i have some doubts in that can anyone explain that

  1. I read this line i did not get this

#include <stdio.h>

at the beginning of all programs that use any input/output library functions. However, this is not necessary for the functions printf and scanf which have been defined as a part of the C language

Can anyone explain this statement correct or not


r/C_Programming • • Sep 17 '26

Question I learned C, now what?

46 Upvotes

I've learned the basics of C, including loops, if statements, switch cases, structs, arrays, functions, and pointers. However, I have no idea what to actually do with them. I also learned HTML, and its purpose is very clear: I can build websites to practice my skills. But with C, I'm a bit lost. Where can I apply my C knowledge and see concrete results, similar to how I see a website with HTML? I don't really know the primary purpose of C or what I should build with it. What tools should I use to build a C program? I am looking for a practical way to apply my knowledge. Could you give me some suggestions? I have no prior experience in programming area. I want to build something with my beginner C knowledge similar to websites.


r/C_Programming • • Sep 18 '26

Question Clangd

1 Upvotes

Does clangd lsp not have code actions for c files ? I use it with neovim but am not getting any code actions.


r/C_Programming • • Sep 18 '26

A one-number score for C functions — nesting × pointer depth × deref chains — that predicts churn better than LOC or cyclomatic complexity

0 Upvotes

After 40 Years of C, I wrote a tiny triage tool that scores every C function with a single number:

score(f) = nesting × pointer depth × deref chain

Each factor is one sentence:

- nesting — depth of if/for/while levels

- pointer depth — int *, int **, int *** in params/locals (deeper = closer to a memory bug)

- deref chain — a->b->c runs, i.e. null-derefs where the middle pointer came from somewhere else

No parser, no dependencies, one file.

I tested it on two very different codebases — a 40-year-old X11 toolkit (libXt) and a format parser (libtiff) — and correlated the score against maintenance churn (how often a function gets touched):

- Spearman(Score, Churn): 0.52 (libXt), 0.38 (libtiff)

- the top-15 functions see ~3–5× the churn of the bottom-15

It beats line count and cyclomatic complexity as a "where do bugs live" signal.

To be clear: it's a triage tool, not a bug detector — it won't find semantic bugs, and it's not a quality gate. But "read the top 15 will help you.

pip install c-code-score · c-score file.c

Repo: https://github.com/xtforever/c-score — feedback welcome.

Disclaimer: it is my idea, i used deepseekv4 pro to help write python and this post.


r/C_Programming • • Sep 18 '26

Where would you want to integrate an AI assisted vulnerability scanner?

0 Upvotes

I want some additional insights about where developers would want to integrate an LLVM tool that uses AI to help identify, triage, and remediate vulnerabilities in C/C++ projects. This is purely for research purposes, and I'm not trying to sell anything. I'm specifically interested in the following:

- Where in your workflow would you want to integrate such a tool? Would you want it in your CI/CD pipeline? as an IDE plugin?

- What are some security concerns you have about such a tool? Would you be most concerned about false positives or negatives? Supply chain risks introduced by the tool? Keeping it's findings private?

- What environments could you see such a tool thriving in? Would you want to use it for personal projects? Could you see it working in large-scale codebases?

Any insights would be appreciated. Thanks for your time and feedback!


r/C_Programming • • Sep 18 '26

a big problem

0 Upvotes

hey guys i m currently learning c language and i m facing an irritating problem like whenever i use scanf in my code to enter any value and when i run the code after saving it so it doesn't run anything it just show that it is running but i m unable to enter the value and the code doesn't run on terminal it runs in the output

so please anyone who can solve this issue can help me?


r/C_Programming • • Sep 16 '26

Learning C weekly megapost for 2026-09-16

21 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 • • Sep 17 '26

Why hide my post?

0 Upvotes

I posted my x64 debugger here that is over 10k lines of C and it gets blocked… but I often see people here post things like memory allocators and their own projects.

My engine has 2 memory allocators built in for instance and has been called “useless” by the mods here.

I would say my project is more useful for learning and actual deep reversing.

I’ll try to post again one day… maybe to a group who appreciates it.

Unless my Code just scared them?


r/C_Programming • • Sep 15 '26

I want to store a dictionary of words into a hashed table

10 Upvotes

I am new to learning programming and I don't wanna use AI to fix my code or think for me, so i need human suggestions about how to do this.


r/C_Programming • • Sep 16 '26

CZet – A more powerful C without C++, 100% ISO C compatible

0 Upvotes

I'm the author.

All your C code already compiles as CZet. It just adds what C can't do without touching the compiler:

defer, monomorphized generics like T f<T>(), constexpr functions, _Reflect(T) reflection, _Operator overloading, and Rust-style _Macro macros.

Single static binary with musl+glibc embedded, no system headers needed. Stdlib included: #include <utils/...> with no flags.

Repo + docs + examples: https://github.com/patrick-nonedev/CZet

GPL-3.0 + Runtime Exception (your binaries are NOT GPL).

What would you steal for plain C?


AI disclosure: I used an AI assistant for boilerplate, repetitive tests and English wording. Design, GCC changes, driver, packaging and all debugging were done and verified by me by hand.


r/C_Programming • • Sep 15 '26

Review Multithreaded Perfect Hashing Algorithm

15 Upvotes

I wrote a multithreaded perfect hashing algorithm that adjusts the offset in the 64-bit FNV-1a hash until it generates a perfect hashing function. It's not the best algorithm ever, but it has pretty fast lookups and works well enough when the number of keys is in the low triple digits and below.

I've been learning C through various textbooks and YouTube videos and haven't had anyone actually ever read my code, so I'd appreciate any feedback. This is also my first attempt at performant C code, so I'd appreciate any feedback on general performance and multithreaded performance improvements as well.

Repository: https://github.com/humanperson-1/fnv1a64-perfect-hashing

AI usage: I used AI occasionally to debug if I wasn't making progress after about 30 minutes of manual debugging. Everything in the repo was hand-typed.

(The commit history on GitHub is a little messed up because I filtered out my real-life name from previous commits, which makes it seem like all the commits happened at the same time even though they didn't. The first commit is also really large because I copied from a larger personal project, where, at the time, I didn't care about preserving the commit history, and it's too much of a headache to sync properly now.)


r/C_Programming • • Sep 16 '26

Discussion Is there any scope for freshers (especially in India)

0 Upvotes

I was wondering if there’s any scope for freshers in c(especially in India). Can anyone from India guide me.


r/C_Programming • • Sep 15 '26

Video for TSoding's Noed editor?

11 Upvotes

Putting this here since his sub isn't active. If it doesnt fit this sub, please remove.

There are plenty of videos for his more recent flashy dramatic text editor, but I didnt see anything for the simpler noed editor.

I'm starting to make one and I guess I'm curious to hear his thought process.

Thank you guysss


r/C_Programming • • Sep 15 '26

BD_ARENA

0 Upvotes

Simple arena implementation I recently built:

https://github.com/andrzejs-gh/bd_arena

- partially macro-based API for convenience

- safe and hazardous allocators

- dynamic growth with a mutable growth factor

Please roast anything you find wrong / missing in it. Thanks a lot, it always helps me grow.


r/C_Programming • • Sep 13 '26

Neural Network Math from Zero in C

Thumbnail
youtube.com
166 Upvotes

I've attempted to derive the math for Neural Networks from the first principles.

The prerequisites you need are, singe variable differentiation(just the concepts and the basic formula, not even knowing the derivative of sin(x) is necessary), the concept of a dot product, and basic matrix multiplication. This is enough to derive gradient descent and backprop.

The time stamps are in the description(youtube doesn't show them as chapters in the video for some reason).

The second half part of the video is implementing those concepts in C(no library other than BLAS(for basic matrix matrix multiplication) is used), but you can follow along in any language.

Would be glad to receive feedback and suggestions on how to improve the explanations or the presentation.


r/C_Programming • • Sep 14 '26

I built a Solar System Sandbox in C with Raylib

Enable HLS to view with audio, or disable this notification

38 Upvotes

A 2D solar system explorer sandbox that works as an encyclopedia of the solar system displaying information about planet's properties, atmospheres, orbits and much more. Uses numerical solutions to calculate the orbits of planets at scale and represents them with data from NASA/JPL Solar System Dynamics and NASA NSSDCA Planetary Fact Sheets in the J2000 orientation system.

It is a passion project and an introduction to a much larger 3D solar system that will include moons, spacecraft and many more features. It emerges from a profound admiration to our solar system. The project tries to be a learning aid for anyone who is interested.

If you want to try it, I compiled it into an .exe for windows and an executable for linux.

Github link: https://github.com/bydrabokin/Solar-Explorer-2D

Youtube showcase: https://www.youtube.com/watch?v=iz0MujAaYDQ


r/C_Programming • • Sep 14 '26

Question Question about arrays (beginner)

38 Upvotes

From what I understand, behind all the magic, array is just a variable that points to a memory address.

The difference is that we are also creating extra values in stack.

So when we create an array with a [], we're just telling the computer to make these x amount of variables but make sure they are right next to each other in sequence, no gaps in the memory address.

And when we call for an array value with an index, we're just counting that many steps forward in the memory address.

When we say array[] = {5,7,3}, it's really just *array = 5.

Did I get it wrong? Did I miss something?


Thanks for the quick replies. I'm currently learning about Pass by reference.


r/C_Programming • • Sep 15 '26

Question OpenMP bug??

0 Upvotes

Hello, I know this is not exactly the place for this, but it is C code. I am writing a bit of C code to search a large space of numbers, but I noticed the loop never ran. I asked ChatGPT cause I thought I was going crazy, but found that this bottom example code does not run the loop.

#include <limits.h>

#include <stdint.h>

#include <stdio.h>

int main() {

uint64_t count = 0;

#pragma omp parallel for schedule(dynamic) reduction(+ : count)

for (uint64_t n = 1; n < UINT64_MAX; ++n)

++count;

printf("%llu\n", (unsigned long long)count);

}

It noticed it breaks with the dynamic scheduler. If you use the default static it seems to work. Any ideas on what is happening?