r/C_Programming • • Feb 23 '24

Latest working draft N3220

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

Learning C weekly megapost for 2026-11-25

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 • • 13h ago

Is there such a problem as "C++ style C"?

28 Upvotes

C++ programmers denounce "C-style C++" that uses primitive C features over newer C++ alternatives. Is the opposite a thing in C where excessive emulation of C++ features become a problem or an antipattern? Some possible examples off my head, no idea how common they actually are or whether they are considered bad; you are welcome to add more:

  • Manual move and copy constructors on resource holders
  • Manual vtables and inheritance
  • Manual closure structs
  • Macro-based template instantiation
  • Opaque generic classes that use all of the above

r/C_Programming • • 3h ago

Question How do you catch fixed-point overflow before it becomes a visible bug?

2 Upvotes

I’m working on some graphics code in C using fixed-point arithmetic. When something looks wrong, it can be hard to tell whether I’ve lost precision or an intermediate calculation has overflowed.

How do you check this while developing? I’m especially interested in catching the first bad calculation, before the result gets passed through several more steps.

AI helped word this question.


r/C_Programming • • 23h ago

If char[] is like a covered pointer, why const char * points to an static piece of memory and char[] creates (or copies from the static) memory in the stack?

17 Upvotes

The title says it all. Im pretty beginner in C and maybe i'm confusing some things with my first afirmation:

> If char[] is like a covered pointer...

I tried to search a lot but my doubts about this subject couldn't get away. (idk why i said in a so metaphorically speaking haha srr)

Thanks!


r/C_Programming • • 12h ago

Barriers, Volatile, and Atomics: How PostgreSQL Orders Memory Accesses

Thumbnail postgr.es
2 Upvotes

r/C_Programming • • 6h ago

Question Need help from senior C programmers

0 Upvotes

Can you all please suggest me the best YT channel (or any other resources) to watch C from, see i kinda know the basics now but the depth is missing, i was seeing yt channels like codewithharry but i think the depth isnt enough, so would be great if anyone helps me out


r/C_Programming • • 1d ago

Tidy translucent typedefs

Thumbnail tavianator.com
34 Upvotes

Recently discovered a nice way to get custom warnings with Clang, so I wrote it up.


r/C_Programming • • 19h ago

Coding a Moiré Fractal with C, Raylib and GLSL

Thumbnail
youtu.be
0 Upvotes

I created a simple moiré fractal using C, raylib and GLSL shaders.

The idea is quite simple: start with two nearby centers and generate concentric circles around each one, gradually increasing their radius.

Then, using the radius as input to a sin function, I generate alternating light and dark values. By applying this to the colors, the two circle patterns interact and produce the characteristic moiré effect.

Complete coding session:

https://youtu.be/7MmUcDiOJDc

Source code:

https://github.com/FractalCodeRicardo/hangover-programming/tree/main/moire-shaders

C / Raylib

#include <raylib.h>
#define size 800

float time = 0.0;

int main() {
  

  InitWindow(size, size, "Moire Circles");

  Shader shader = LoadShader(0, "moire.glsl");
  
  int timeLoc = GetShaderLocation(shader, "time");
  while (!WindowShouldClose()) {

    time = GetTime();
    SetShaderValue(shader, timeLoc, &time, SHADER_UNIFORM_FLOAT);

    BeginDrawing();
      BeginShaderMode(shader);
        DrawRectangle(0, 0, size, size, BLACK);
      EndShaderMode();
    EndDrawing();
  }

  CloseWindow();
}

Glsl

#version 330

out vec4 color;

uniform float time;

void main() {
  vec2 uv = gl_FragCoord.xy / 800;
  uv = uv - 0.5;
  
  float a = 30;

  vec2 center1 = vec2(0.1, 0.0);
  vec2 center2 = vec2(-0.1, 0.0);
  
  float d1 = distance(center1, uv);
  float d2 = distance(center2, uv);

  vec4 color1 = vec4(
      0.0 * sin(a * time*d1),
      0.8 * sin(a * time*d1),
      0.8 * sin(a * time*d1),
      1
  );

  vec4 color2 = vec4(
      1 * sin(a * time*d2),
      0.2 * sin(a * time*d2),
      1 * sin(a * time*d2),
      1
  );
  
  color = mix(color1, color2, 0.5);
}

AI Disclaimer:

I did not use AI to code the fractal.


r/C_Programming • • 17h ago

Project cortex (`cx`) – A Cargo/uv-inspired package manager and build tool for C and C++

Thumbnail
github.com
0 Upvotes

Hello!

I’ve been working on cortex (cx), a C/C++ package manager and build tool inspired by Rust’s Cargo and Python’s uv, and I’d love to share it with you and get some feedback.

Why another tool?

Setting up a C++ project with clean dependency management, lockfiles, features, and workspaces often requires gluing together multiple tools and boilerplate CMakeLists.txt files. With cx, you describe your package in a single cx.toml file, it resolves and locks dependencies, generates the underlying CMake project, and drives the build automatically.

Quick example

cx new hello
cd hello
cx add nlohmann_json --git https://github.com --tag v3.12.0
cx run

Key Features

Zero-boilerplate builds: Sources, tests, benchmarks, and examples are discovered by convention (src, tests, benches, examples). Supports mixed C (C90–C23) and C++ (C++98–C++26), including C++20 modules (.cppm, .ixx).

Flexible dependency management: Pull dependencies from registries, Git repos, local paths, system packages (find_package), or vcpkg. Any existing CMake, Autotools, or SCons project works out of the box as a Git or path dependency.

PubGrub version resolution & lockfiles: Uses the PubGrub solver (like uv and pub) for clear conflict explanations, and pins exact versions, Git commits, and SHA-256 hashes in cx.lock.

Cargo-style features & workspaces: Supports optional dependencies, feature flags (exposed via CX_FEATURE_ macros), and multi-package workspaces sharing a single lockfile and target/ directory.

Built-in developer workflows: Comes with cx test, cx bench, cx fmt (clang-format), cx lint (clang-tidy), cx doc (Doxygen), cx vendor for offline builds, and built-in sanitizer/LTO build profiles.

IDE & CI friendly: Generates standard CMake projects (cx generate) and JSON metadata (cx metadata) so your existing IDE setup works seamlessly, plus --locked and --offline flags for CI.

Current Status & Caveats

First Release & Self-Hosting: This is the very first release. Right now the repo still includes its bootstrapping CMake files, which will be removed in the next release now that cx can build itself.

OS Support: Works on Linux and macOS. Windows (MSVC) support is newly added and passing in CI, though it hasn't been battle-tested in the wild yet.

Public Registry: There isn't a central public registry yet, though cx works directly with Git repositories, local paths, vcpkg, system packages, and includes a lightweight self-hosted registry server (cx-registry).

Links

GitHub Repository

The cx Book (Documentation)

You can install prebuilt binaries via the install script in the README or build it from source with CMake 3.28+ and a C++23 compiler. 

I’d really appreciate any feedback, bug reports, or thoughts on what would make this genuinely useful for your C/C++ workflows!

Use of AI: this text has been formatted with AI, the code was built using AI assistance to save time.

Thanks


r/C_Programming • • 2d ago

Discussion Why did C++ crush Objective-C in popularity?

176 Upvotes

I know C and C++ are largely source-compatible with each other, but Objective-C is specifically a strict superset of C, not just a fork of it, like C++. You’d think that scratching that OOP itch while also giving you complete source compatibility with C would cause more companies or projects to utilize it, at least in some respect, but that may just be a naïve prediction. What does C++ have that Objective-C doesn’t that you think caused such a large popularity gap between the two languages? Am I missing some nuance?


r/C_Programming • • 1d ago

I have an issue that I haven't figured out even with 3 weeks of debugging

3 Upvotes

Here is uefi_graphics.c:

#include <inc/efi.h>
#include <inc/efilib.h>
#include "helper.h"


#define ACPI_DEVICE_PATH 0x02
#define ACPI_ADR_DP 0x03


bool memcmp(char *a, char *b, int len) {
    for (int i = 0; i < len; i++) {
        if (a[i] != b[i]) return false;
    }
    return true;
}


EFI_GUID gop_guid = EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID;
EFI_GUID device_path_guid = EFI_DEVICE_PATH_PROTOCOL_GUID;
EFI_GUID edid_guid = EFI_EDID_DISCOVERED_PROTOCOL_GUID;


int fb_count;


bool check_if_fb_usable(EFI_HANDLE gop_handle, EFI_EDID_DISCOVERED_PROTOCOL *edid, EFI_HANDLE edid_handle);
bool match_output(EFI_DEVICE_PATH_PROTOCOL *gop_path, EFI_DEVICE_PATH_PROTOCOL *edid_path);
EFI_DEVICE_PATH_PROTOCOL *get_device_path(EFI_HANDLE handle);
EFI_DEVICE_PATH_PROTOCOL *find_adr_node(EFI_DEVICE_PATH_PROTOCOL *path);


const uint8_t ref_edid_header[8] = {
    0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00
};


bool match_output(EFI_DEVICE_PATH_PROTOCOL *gop_path, EFI_DEVICE_PATH_PROTOCOL *edid_path);


framebuff_t *get_framebuff() {
    framebuff_t *_fb;


    EFI_GRAPHICS_OUTPUT_PROTOCOL *gop;
    EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE *mode;
    EFI_EDID_DISCOVERED_PROTOCOL *edid = NULL;


    EFI_HANDLE *handles = NULL;
    uint32_t handle_count = 0;


    EFI_HANDLE *edid_handles = NULL; //for normal edid
    int edid_handle_count = 0;



    BS->LocateHandleBuffer(ByProtocol, &gop_guid, NULL, (UINTN*)&handle_count, &handles);
    BS->LocateHandleBuffer(ByProtocol, &edid_guid, NULL, (UINTN*)&edid_handle_count, &edid_handles);


    //allocate memory for framebuffer data


    BS->AllocatePool(EfiLoaderData, (sizeof(framebuff_t) * handle_count) / 4096 + 1, (void**)&_fb);



    for (int i = 0; i < handle_count; i++) {
        BS->HandleProtocol(handles[i], &gop_guid, (void**)&gop);


        mode = gop->Mode;
        
        for (int j = 0; j < edid_handle_count; j++) {
            if (check_if_fb_usable(handles[i], edid, edid_handles[j])) {
                _fb[i].buff = (void*)mode->FrameBufferBase;
                _fb[i].width = mode->Info->HorizontalResolution;
                _fb[i].height = mode->Info->VerticalResolution;
                _fb[i].size = mode->FrameBufferSize;
                _fb[i].stride = mode->Info->PixelsPerScanLine * 4;
            
                if (mode->Info->PixelFormat == PixelBltOnly) break;
            
                if (mode->Info->PixelFormat == PixelBitMask) {
                    EFI_PIXEL_BITMASK mask = mode->Info->PixelInformation;
                    _fb[i].pixel_layout[0] = mask.RedMask;
                    _fb[i].pixel_layout[1] = mask.GreenMask;
                    _fb[i].pixel_layout[2] = mask.BlueMask;
                    _fb[i].pixel_layout[3] = mask.ReservedMask;
                }


                if (mode->Info->PixelFormat == PixelRedGreenBlueReserved8BitPerColor) {
                    _fb[i].pixel_layout[0] = 0x000000FF;
                    _fb[i].pixel_layout[1] = 0x0000FF00;
                    _fb[i].pixel_layout[2] = 0x00FF0000;
                    _fb[i].pixel_layout[3] = 0xFF000000;
                }


                if (mode->Info->PixelFormat == PixelBlueGreenRedReserved8BitPerColor) {
                    _fb[i].pixel_layout[0] = 0x00FF0000;
                    _fb[i].pixel_layout[1] = 0x0000FF00;
                    _fb[i].pixel_layout[2] = 0x000000FF;
                    _fb[i].pixel_layout[3] = 0xFF000000;
                }
            }
        }
            fb_count++;
    }
    BS->FreePool(handles);
    BS->FreePool(edid_handles);


    return _fb;
}


bool check_if_fb_usable(EFI_HANDLE gop_handle, EFI_EDID_DISCOVERED_PROTOCOL *edid, EFI_HANDLE edid_handle) {


    for (int i = 0; i < 8; i++) {
        if (edid->Edid[i] != ref_edid_header[i]) {
            return false;
        }
    }


    return match_output(get_device_path(gop_handle), get_device_path(edid_handle));
}


EFI_DEVICE_PATH_PROTOCOL *get_device_path(EFI_HANDLE handle) {
    EFI_DEVICE_PATH_PROTOCOL *path = NULL;
    BS->HandleProtocol(handle, &device_path_guid, (void**)&path);


    return path;
}


EFI_DEVICE_PATH_PROTOCOL *find_adr_node(EFI_DEVICE_PATH_PROTOCOL *path) {
    while (!IsDevicePathEnd(path)) {


        if (path->Type == ACPI_DEVICE_PATH && path->SubType == ACPI_ADR_DP) return path;


        path = NextDevicePathNode(path);


    }


    return NULL;
}


bool match_output(EFI_DEVICE_PATH_PROTOCOL *gop_path, EFI_DEVICE_PATH_PROTOCOL *edid_path) {
    EFI_DEVICE_PATH_PROTOCOL *gop_adr = find_adr_node(gop_path);


    EFI_DEVICE_PATH_PROTOCOL *edid_adr = find_adr_node(edid_path);


    if (!gop_adr || !edid_adr) return false;


    uint32_t gop_offset = (uint32_t)((uint8_t*)gop_adr - (uint8_t*)gop_path);
    uint32_t edid_offset = (uint32_t)((uint8_t*)edid_adr - (uint8_t*)edid_path);


    if (gop_offset != edid_offset) return false;


    if (!memcmp((char*)gop_path, (char*)edid_path, gop_offset)) return false;


    uint32_t gop_length = DevicePathNodeLength(gop_adr);
    uint32_t edid_length = DevicePathNodeLength(edid_adr);


    if (gop_length < 8 || edid_length < 8 || (gop_length - 4) % 4 != 0 || (edid_length - 4) % 4 != 0) return false;


    uint32_t gop_count = (gop_length - 4) / 4;
    uint32_t edid_count = (edid_length - 4) / 4;


    if (edid_count != 1) return false;


    uint32_t *edid_adr_value = (uint32_t*)((uint8_t*)edid_adr + 4);


    uint32_t *gop_adr_value;


    for (int i = 0; i < gop_count; i++) {
        gop_adr_value = (uint32_t*)((uint8_t*)gop_adr + 4 + i * 4);


        if (*gop_adr_value == *edid_adr_value) return true;
    }


    return false;
}

Here is boot.c:

#include <inc/efi.h>
#include <inc/efilib.h>
#include "helper.h"
#include "../include/mmp_mem_map.h"


#define COM 0x3F8


void init_serial() {
    koutb(COM + 1, 0x00);
    koutb(COM + 3, 0x80);


    koutb(COM, 0x03);
    koutb(COM + 1, 0x00);


    koutb(COM + 3, 0x03);
    koutb(COM + 2, 0xC7);
    koutb(COM + 4, 0x0B);
}


void serial_putc(char c) {
    while ((kinb(COM+5) & 0x20) == 0);
    
    koutb(COM, c);
    return;
}


void print_serial(char *s) {
    while (*s) {
        serial_putc(*s);
        s++;
    }
    return;
}


#define KERNEL_BASE 0xFFFFFFFF80000000


EFI_BOOT_SERVICES *BS;


#define PRINT_CONSOLE_(msg) print_serial(msg)
#define PRINT_CONSOLE(msg) sys_tbl->ConOut->OutputString(sys_tbl->ConOut, msg)
void (__attribute__((sysv_abi)) *kernel_start)(uint64_t usable_mem, void *mem_map, int mem_map_len, void *fb, int fb_count, void *kernel_pwt);


//declare global variables
void *kernel_pwt = (void*)0xFFFFFFFF;
uint64_t total_mem = 0;
int mem_map_len = 0;


void load_kernel(EFI_HANDLE image_handle);
mem_map_t *get_memory_map(EFI_HANDLE image_handle);


EFI_SYSTEM_TABLE *sys_tbl;


EFI_STATUS efi_main(EFI_HANDLE image_handle, EFI_SYSTEM_TABLE *_sys_tbl) {
    sys_tbl = _sys_tbl;
    BS = sys_tbl->BootServices;
    PRINT_CONSOLE(L"This is the bootloader of JOS. It's job is to load the kernel into memory, give the kernel a memory map, get a framebuffer to all screens (hopefully), and map memory.\n");


    PRINT_CONSOLE(L"Loading kernel to memory...\n");
    load_kernel(image_handle);
    PRINT_CONSOLE(L"kernel loaded into memory sucessfully at 0x100000.\n");


    PRINT_CONSOLE(L"Acquiring framebuffer(s)..\n");
    framebuff_t *fb = get_framebuff();
    PRINT_CONSOLE(L"Framebuffer(s) aquired succesfully.\n");


    PRINT_CONSOLE(L"Acquiring memory map...\n");
    map_pages(0x100000, 0x100000 / 4096, kernel_pwt);
    mem_map_t *kmem_map = get_memory_map(image_handle);
    
    //enter_kernel(total_mem, kmem_map, mem_map_len, fb, fb_count, kernel_pwt);
    return EFI_SUCCESS;
}


//define GUIDs
EFI_GUID loaded_img_guid = EFI_LOADED_IMAGE_PROTOCOL_GUID;
EFI_GUID simple_fs_guid = EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID;
EFI_GUID file_info_guid = EFI_FILE_INFO_ID;



void load_kernel(EFI_HANDLE image_handle) {
    EFI_LOADED_IMAGE *kernel_img;
    EFI_FILE_IO_INTERFACE *fs;
    EFI_FILE *root, *file;


    sys_tbl->BootServices->HandleProtocol(image_handle, &loaded_img_guid, (void**)&kernel_img);


    sys_tbl->BootServices->HandleProtocol(kernel_img->DeviceHandle, &simple_fs_guid, (void**)&fs);


    fs->OpenVolume(fs, &root);


    //open kernel file
    root->Open(root, &file, L"\\kernel.img", EFI_FILE_MODE_READ, 0);


    EFI_FILE_INFO *info;
    UINTN info_size = SIZE_OF_EFI_FILE_INFO + 200;
     
    BS->AllocatePool(EfiLoaderData, info_size, (void**)&info);
    file->GetInfo(file, &file_info_guid, &info_size, info);
    UINTN file_size = info->FileSize;


    UINTN pages = (file_size + 0xFFF) / 4096;
    EFI_PHYSICAL_ADDRESS addr = 0x100000;
    BS->AllocatePages(AllocateAddress, EfiLoaderData, pages, &addr);


    UINTN read_size = file_size;
    file->Read(file, &read_size, (void*)addr);


    file->Close(file);


    BS->AllocatePages(AllocateMaxAddress, EfiLoaderData, 1, (EFI_PHYSICAL_ADDRESS*)&kernel_pwt);
    BS->SetMem(kernel_pwt, 4096, 0);


    EFI_LOADED_IMAGE_PROTOCOL *efi_app;


    BS->HandleProtocol(image_handle, &loaded_img_guid, (VOID **)&efi_app);


    for (int i = 0; i < (file_size + 4095) / 4096; i++) {
        map_pages(KERNEL_BASE + ((uint64_t)i * 4096), (addr / 4096) + i, kernel_pwt);
    }
    for (int j = 0; j < efi_app->ImageSize; j+=4096) {
        map_pages((uint64_t)efi_app->ImageBase + (uint64_t)j, ((uint64_t)efi_app->ImageBase + (uint64_t)j) / 4096, kernel_pwt);
    }
    return;
}


mem_map_t *get_memory_map(EFI_HANDLE image_handle) { //also maps phys_map
    mem_map_t *kmem_map;
    EFI_MEMORY_DESCRIPTOR *mem_map;
    UINTN mem_map_size = 0;
    UINTN map_key, desc_size;
    UINT32 desc_version;


    sys_tbl->BootServices->GetMemoryMap(&mem_map_size, NULL, &map_key, &desc_size, &desc_version);


    mem_map_size *= 2;


    BS->AllocatePages(AllocateAnyPages, EfiLoaderData, mem_map_size / 4096 + 1, (EFI_PHYSICAL_ADDRESS*)&mem_map);


    BS->AllocatePages(AllocateAnyPages, EfiLoaderData, mem_map_size / 4096 + 1, (EFI_PHYSICAL_ADDRESS*)&kmem_map);


    BS->GetMemoryMap(&mem_map_size, mem_map, &map_key, &desc_size, &desc_version);


    //build kernel memory map
    
    EFI_MEMORY_DESCRIPTOR *desc;


    int i;


    for (int offset = 0; offset < mem_map_size; offset += desc_size) {
        desc = (EFI_MEMORY_DESCRIPTOR*)((char*)mem_map + offset);
        i = offset / desc_size;
        
        kmem_map[i].start = (void*)desc->PhysicalStart;
        kmem_map[i].end = (void*)(desc->PhysicalStart + (desc->NumberOfPages * 4096));
        
        if (desc->Type == EfiReservedMemoryType || (desc->Type == EfiLoaderData && desc->PhysicalStart == kmem_map) ||desc->Type == EfiUnusableMemory
            || desc->Type == EfiACPIReclaimMemory || desc->Type == EfiACPIMemoryNVS || desc->Type == EfiMemoryMappedIOPortSpace ||
            desc->Type == EfiPalCode || desc->Type == EfiPersistentMemory || desc->Type == EfiUnacceptedMemoryType) kmem_map[i].flags = 1;
        
        else if (desc->Type == EfiMemoryMappedIO) kmem_map[i].flags = 3;
        else {
            kmem_map[i].flags = 0; 
        }
        if (offset + desc_size > mem_map_size) {
            break;
        }
        total_mem += (uint64_t)kmem_map[i].end - (uint64_t)kmem_map[i].start;
        mem_map_len++;
    }


    for (uint64_t j = 0; j < total_mem; j+=4096) { //start mapping kernel's phys_map starting at 0x8FFFFFFFFFFFFFFF
        map_pages(0xFFFF800000000000 + j, j / 4096, kernel_pwt);
    }


    BS->GetMemoryMap(&mem_map_size, mem_map, &map_key, &desc_size, &desc_version); //for correct map key
    BS->ExitBootServices(image_handle, map_key);


    return kmem_map;
}

enter_kernel.s:

.intel_syntax noprefix
.global enter_kernel
.global print_serial
.global koutb
.global kinb
//R9 is pml4 root


.section .data
msg1: .asciz "enter_kernel reached\n"
msg2: .asciz "arguments loaded\n"


.section .text


koutb:
    mov dx, di
    mov al, sil


    out dx, al
    ret


kinb:   
    mov dx, di


    in al, dx
    ret



enter_kernel: //this is okay for now since QEMU UEFI implementation uses 4 level paging, implement change from 5 level paging later
    cli


    //put arguments correctly according to System-V
    mov rdi, rcx
    mov rsi, rdx
    mov rdx, r8
    mov rcx, r9


    mov r8, [rsp+40]
    mov r9, [rsp+48]


    mov rax, 0x100000


    jmp rax

boot_helper_x86_64.c:

#include <inc/efi.h>
#include <inc/efilib.h>


uint64_t get_ptr_from_entry(void* entry) {
    return ((uint64_t)entry & ~0xFFFULL);
}


uint64_t construct_entry(uint64_t addr, uint16_t flags) {
    return (addr & ~0xFFFULL) | (uint64_t)flags;
}


void map_pages(uint64_t va, uint32_t page, void *pwt_base) {
    uint16_t flags = 0x3;


    uint16_t indexes[4];
    indexes[0] = (va >> 39) & 0x1FF; //pml4 index
    indexes[1] = (va >> 30) & 0x1FF; //pdpt index
    indexes[2] = (va >> 21) & 0x1FF; //pd index
    indexes[3] = (va >> 12) & 0x1FF; //pt index


    void **pml4, **pdpt, **pd, **pt;
    pml4 = pwt_base;
    uint64_t ptr;


    pdpt = (void*)get_ptr_from_entry(pml4[indexes[0]]);


    if (pdpt == NULL) {
        BS->AllocatePages(AllocateAnyPages, EfiLoaderData, 1, &ptr);
        BS->SetMem((void*)ptr, 4096, 0);
        pml4[indexes[0]] = (void*)construct_entry(ptr, flags);
        pdpt = (void*)get_ptr_from_entry(pml4[indexes[0]]);
    }
    pd = (void*)get_ptr_from_entry(pdpt[indexes[1]]);
    if (pd == NULL) {
        BS->AllocatePages(AllocateAnyPages, EfiLoaderData, 1, &ptr);
        BS->SetMem((void*)ptr, 4096, 0);
        pdpt[indexes[1]] = (void*)construct_entry(ptr, flags);
        pd = (void*)get_ptr_from_entry(pdpt[indexes[1]]);
    }
    pt = (void*)get_ptr_from_entry(pd[indexes[2]]);
    if (pt == NULL) {
        BS->AllocatePages(AllocateAnyPages, EfiLoaderData, 1, &ptr);
        BS->SetMem((void*)ptr, 4096, 0);
        pd[indexes[2]] = (void*)construct_entry(ptr, flags);
        pt = (void*)get_ptr_from_entry(pd[indexes[2]]);
    }
    pt[indexes[3]] = (void*)construct_entry((uint64_t)page * 4096, flags);


    return;
}

For context, my kernel uses System-V. When I try to run this in QEMU, my kernel is never reached. It freezes after get_memory_map. And yes, the code is messy, yes it has very questionable arcitechture / design choices, yes, it is terrible. But please help me out.


r/C_Programming • • 2d ago

Question What happened to Muukid libraries?

9 Upvotes

I am trying to find some C libraries created by a developer named Muukid.

He created muDOG, muCOSA, and muGraphics. He also had a YouTube channel where he showcased his libraries in hour-long videos, but it seems the channel has been deleted. The links to the channel no longer work, and his GitHub page also appears to have vanished.

Does anyone know if these projects are still available anywhere? I am particularly interested in finding archived copies of muDOG and muCOSA, as I was only able to clone muGraphics.

Any information would be greatly appreciated.


r/C_Programming • • 2d ago

Four Years of development in C

Thumbnail
github.com
10 Upvotes

Exactly four years ago, I started working on BouncyCastle - a cryptographic key storage simulator with a PKCS#11 interface, a REST API, and a web management interface. It is designed for developers working with HSMs and smart cards, as well as for QA environments.

At the time development of SoftHSMv2 (C++) began, it was practically dead (in 2022), and bugs weren’t even being fixed, moreover, it had architectural issues (SIGSEV if you used the application with the wrong version of OpenSSL, problems with multi-user access, poor logging, poor cross-platform compatibility, and support for different algorithms on different platforms).

Note: Kryoptic (Rust) was created later, but it merely ported all of SoftHSMv2’s problems from C++ to Rust.

BouncyHsm has a native PKCS#11 library in C (exporting over 100 functions) and a backend written in C# where cryptographic operations are performed (supporting 210 mechanisms) - one could say, with a bit of hyperbole, that it is a network HSM.

Why I chose C for the native PKCS#11 library. I considered several options and even experimented with them:

  • C# - starting with .NET 7, it can create native libraries, but I was worried that the garbage collector would bloat the binary (a simple REST client was 8 MB, in later versions, it was only about half a megabyte),
  • Rust - while experimenting with Rust, I realized I’d end up with a huge amount of unsafe code and exceptions for different platforms. I was also concerned about the dependencies that the libraries would introduce,
  • Zig - it’s still not at version 1.0.

Ultimately, my experiments showed that pure C would be best for this project, without any external dependencies, using Messagepack for RPC (via the one-file library cmp) and TCP via the operating systems API. One of the specific requirements I set for myself was that the PKCS#11 library must not have any external dependencies to prevent crashes. Another advantage is that you can even compile it for your "refrigerator or toothbrush".

What I've learned from developing in C over the past 4 years, and what I would do differently:

  • I've come to love the WinAPI - yes, it sounds strange, but low-level programming on Windows is a million times better than on UNIX systems. Because theres an API for everything, on Linux, I had to parse a lot of things from text files,but be careful - some Linux distributions have them in a different directory, and some use a different format. It was a pain.
  • glibc - and its various versions on Linux - be damn careful with this.
  • be careful with online tutorials, because they’ll recommend code that uses extensions that only work in gcc/clang.
  • instead of one big Makefile, I’ve found it works best to have several small ones - one for Linux and one for macOS (I also have one for MinGW, but on Windows I use MSVC).
  • For a long time, I resisted using goto (goto clean/goto error) and tried to write code without it; in hindsight, I regret that, because it complicated memory management for me (I’m waiting for the C2Y standard and defer).
  • It’s a good idea to have your code checked by AI, it can find silly mistakes like memory leaks.
  • Don’t trust AI - it’ll suggest things it’s seen on forums, even if they aren’t part of the standard.
  • When you start an open-source project, people will want you to fix bugs in it.

P.S.: This was originally supposed to be a short post, but it kind of got out of hand. If you have any questions, feel free to ask.


r/C_Programming • • 2d ago

three different approaches to an example in Fluent C book

8 Upvotes

Reading a post a few days ago, I looked for a book about C that had a Patterns approach along the lines of Design Patterns: Elements of Reusable Object Oriented Software and finally settled on Fluent C: Principles, Practices, and Patterns by Christopher Preschern.

The first chapter is about error handling where the author starts with a single function of a very simple file reader full of if statements and partitions it out into three different functions: allocation of resources, using the resources, deallocation of the resources. The resources are a file handle with access to provide read access to a text file and a large buffer to read the lines of text.

Here are three different approaches to managing the resources while using the resources is the same function for all three different approaches.

What are Pros and Cons of each? Is there one of the alternatives you feel is the most appropriate approach? Is there a fourth alternative you think better than these?

The first makeParser() and closeParser() functions are similar to Preschern's code except that what he does in two calls to malloc(), I do with a single call.

The second version is not allocating memory for the Parser variable but instead is using a stack allocation with a C99 Compound Literal to create a variable whose address is then passed into the second version of makeParser2().

The third version uses the same makeParser() as the first one however the closeParser3() function differs in that it is the responsibility of the caller to free the allocated memory.

An interesting point is that the three alternatives all use the same useParser() function.

#include <stdio.h>
#include <memory.h>
#include <stdbool.h>

typedef struct {
    bool   bValid;    // whether the Parser object is valid or not
    FILE* pFile;      // the file which is being processed
    void* pBuff;      // the address of the I/O buffer
} Parser;

#define MAX_FILE_BUFFER_SIZE  400


Parser* makeParser(const char* filename)
{
    Parser* p = NULL;

    // allocate the needed memory all in a single block to make free() easy.
    // this also ensures that all needed memory is available.
    p = malloc(sizeof(Parser) + MAX_FILE_BUFFER_SIZE);
    if (p) {
        // allocate resources and mark if valid when all
        // resources are allocated.
        p->pBuff = p + 1;    // the I/O buffer begins after the Parse struct.
        p->pFile = fopen(filename, "r");
        p->bValid = (p->pFile != NULL);
    }
    return p;
}

Parser* makeParser2(Parser* p, const char* filename)
{
    Parser  x = { .bValid=false, .pFile=NULL, .pBuff=NULL };

    if (p) {
        // allocate resources and mark if valid when all
        // resources are allocated.
        if ((x.pFile = fopen(filename, "r")) != NULL) {
            x.pBuff = malloc(MAX_FILE_BUFFER_SIZE);
            x.bValid = (x.pBuff != NULL);
        }

        *p = x;
    }
    return p;
}


int useParser(Parser* p)
{
    int iRet = 0;

    if (p && p->bValid) {
        while (fgets(p->pBuff, MAX_FILE_BUFFER_SIZE, p->pFile) != NULL) {
            printf(p->pBuff);   // the line will have next line when read as text
        }
        iRet = 1;
    }

    return iRet;
}

Parser * closeParser(Parser* p)
{
    if (p) {
        // free the resources and mark as invalid.
        if (p->pFile) fclose(p->pFile);
        *p = (Parser){ .bValid = false, .pFile = NULL, .pBuff = NULL };
        free(p);
        p = NULL;
    }

    return p;
}

Parser * closeParser2(Parser* p)
{
    if (p) {
        // free the resources and mark as invalid.
        if(p->pBuff) free(p->pBuff);
        if (p->pFile) fclose(p->pFile);
        *p = (Parser){ .bValid=false, .pFile=NULL, .pBuff=NULL };
        p = NULL;
    }

    return p;
}

Parser * closeParser3(Parser* p)
{
    if (p) {
        // free the resources and mark as invalid.
        // pBuff is part of the memory allocated for p so no free
        if (p->pFile) fclose(p->pFile);
        *p = (Parser){ .bValid = false, .pFile = NULL, .pBuff = NULL };
    }

    return p;
}


int main()
{
    const char fileName[] = "decompressed.txt";
    int iRetToss = 0;

    {
        Parser* p = makeParser(fileName);
        iRetToss = useParser(p);
        p = closeParser(p);
        iRetToss++;    // place for a break point to inspect p
    }

    {
        Parser* p = makeParser2(&((Parser) { .bValid = false, .pFile = NULL, .pBuff = NULL }), fileName);
        iRetToss = useParser(p);
        p = closeParser2(p);
        iRetToss++;    // place for a break point to inspect p
    }

    {
        Parser* p = makeParser(fileName);
        iRetToss = useParser(p);
        p=(free(closeParser3(p)), NULL);
        iRetToss++;    // place for a break point to inspect p
    }

    return iRetToss;
}

r/C_Programming • • 3d ago

Best Way to Read 'Raw Data'

19 Upvotes

I'm writing a C program for the pi pico and realized I never really figured out how to properly cast characters to raw bytes then to other things, or if there was really a way to do that.

  1. Does char mean "signed char" by default in any C program, or is that up to interpretation by the compiler?
  2. Would using a void pointer to dereference then recast to *uint8_t work?
  3. When bytes are read through getc(), are the bytes modified before they are stored? As in, how are the bytes that are read interpreted to translate to characters, and how are they stored? My initial thought was that the bytes were interpreted "as-is", meaning that they were copied directly to the memory in the character and interpreted as signed characters. But it seems like they're being reinterpreted in some way as they are cast.
  4. If something about the process is too implementation specific, is reading as "raw data" just a flat out bad idea or not supported at all? Will the behavior be undefined on other systems? As long as I can get it to work on the pico it's fine, it doesn't have to be portable. But for future reference, should I not try to think of things as "raw data" unless the implementation specifically defines how it stores the data?
  5. Less important, but how are ascii codes mapped to signed characters? (every chart I've seen has never listed a negative number, only 0-255) (( and if signed is the standard, then why does every asii chart list 0-255... ))

// this was the void pointer way I was going to try, would this work?

tnext =  *((uint8_t*)((void*)&next));  // Cast to uint8_t

(Not sure if this is a repeat but I couldn't find exactly what I was looking for. Sorry if this is a dupe)

Conclusion: Seems like when you read getc() you just need to indicate "unsigned char" so that the byte is read unmodified and can be cast directly to a "uint8_t"? I think the reason I hadn't done that originally was because I thought "but getc returns char, not unsigned char", but I dont think that matters. getc should read into either


r/C_Programming • • 2d ago

cc_list: an intrusive doubly linked list, faster than Linux kernel's list_head and BSD TAILQ

Thumbnail
github.com
3 Upvotes

cc_list is cc_task (async/await closure coroutine library in C) 's linked list implementation.

It's node points directly to the next container, not next node; so you don't need to do `container_of` to get the container.

Linux kernel's list_head is classic, it's node pointers to next node, perform container_of, just a sub CPU instruction, to get the container.

cc_list optimized away this sub instruction so it's even faster than linux's list_head!
And using cc_list is just similar like using list_head.

The head is not a container, just a node with prev/next pointers. The trick is when empty, head points to a non-existed shadow container, just point but no dereference, so it's safe.

┌─────────────────────────────────────────────┐
└►........... ┌─►┌─────────┐ ┌─►┌─────────┐   │
  :  shadow : │  │container│ │  │container│   │
  :         : │  │         │ │  │         │   │
  :         : │  │         │ │  │         │   │
  ├─────────┤ │  ├─────────┤ │  ├─────────┤   │
  │   head  ├─┘  │   node  │─┘  │   node  │───┘
  ├─────────┤    ├─────────┤    ├─────────┤
  ...........    └─────────┘    └─────────┘

r/C_Programming • • 3d ago

Question A beginner in C ... Is building a shell a good beginner project ..if so what are the resources that i can follow to create it...

11 Upvotes

r/C_Programming • • 4d ago

Video Brian Kernighan: Inside Bell Labs, The Best Programmer, Why C Won

98 Upvotes

Interesting video by Ryan Peterman:

https://www.youtube.com/watch?v=sMllOlxVgD0

Timestamps: 
1:21 C was always the fastest.
1:22 C++ wasn't as fast as I thought it would be.

00:00    Intro 
00:42    What Bell Labs was and how he got hired 
06:34    Why so many inventions came from Bell Labs 
14:15    A day in the life at Bell Labs 
27:55    The most impressive people he worked with 
33:50    The AT&T film explaining Unix 
39:46    Why C was so influential 
43:25    How awk was created 
48:40    What he misses most about Bell Labs 
54:10    Are LLMs bad for computer science education 
01:01:46 His 1972 commit in the Go repo 
01:03:43 Grace Emlen, the fake Bell Labs employee 
01:07:39 Why he writes so many books 
01:19:58 His favorite and least favorite languages 
01:24:28 Advice for students and young people 
01:27:42 Outro

r/C_Programming • • 2d ago

Question Hi! I am using visual studio but it doesn't work. error: "missing filename after '-o'" what should i do?

0 Upvotes

r/C_Programming • • 3d ago

Discussion Revealed vs. Opaque structs for Libraries

5 Upvotes

Hi all, I'm developing a win32 windowing library for mostly myself but also want it to be easy and intuitive to use and follow good C standards.

In my library have the main object window_t that is used for mostly everything. However, I'm wondering between a couple different design decisions for it:

// public .h
typedef struct window_t window_t;

window_t* createWindow(...); << createWindow heap allocates a window_t

void destroyWindow(window_t* window);

2.

// public .h

typedef struct window_t { implementation... ) window_t;

void createWindow(window_t* out, ...);

// no destroyWindow

the difference I'm looking is that for #1, the user mantains control of the heap allocated memory through createWindow() and must free it after they're done using it, but for #2 the user can create a stack allocated window and it doesn't need to be freed, however it removes the opaque struct safeness in #1.

Are there any pros/cons for either method I haven't thought of? My instinct tells me that #2 seems better as the user controls the memory allocation, they just need to be careful how they use the window_t.

Thoughts?


r/C_Programming • • 3d ago

Project IncHash - A Disk Based Hash Table with NoSQL ambitions.

Thumbnail
github.com
4 Upvotes

Brief

A general-purpose, header-only C99 library for Unix-like systems, implementing a disk-based, dynamically resizable, fixed-slot, (open-addressed) hash table with Fibonacci hashing (Knuth's multiplicative method), triangular probing, per-home-slot probe-bound metadata (with additional early-exit logic), partial in-place value updates (without relocating entries) and incremental rehashing, all designed for modern extent-based filesystems.

Disclosure

This is not a vibe-coded project! I painstakingly wrote everything myself (including this post :P). of course that being said, it doesn't mean that I didn't use AI for reasearch, brainstorming and a bit of testing. I have talked about it here as well.

Prologue

This is a project I've shared here before, a few months ago. Back then, being relatively inexperienced with hash table implementation, I inadvertently introduced a few bugs.

Since then, thanks to a lovely Redditor who took the time to provide some truly valuable feedback (for which I'm genuinely and wholeheartedly grateful), I've made quite a few promising improvements, including: recovery validation methods and CRC checksums, an inchash_mod-function for partial in-place value updates\modifications (without relocating entries), a fuzz-style regression test, refactoring of core-metadata, and of course, fixing those bugs (or so I hope lol).

Having said and done all those improvements, I though it would be the right move to expose my project, for once again in the intelectual wilderness of reddit xD. So here I am ready to hear what you thinking about it.

Intro

All started with me trying to find:

A hash-based NoSQL (key-value pair) database with mutable-values (by mutable I mean: a database that allows editing prexisting [fixed-size] values without having to rewrite or remap the whole value again eg. Just edit a few bytes and put those bytes back to the original value-space without rewriting the whole value).

I made this for a larger project I'm working on, which I haven’t released yet.

Outro

I'm really excited and scared because idk what you all gonna find again... but I hope you all find it at least interesting and enjoy playing around with it.

That said, thank you for reading this and feel free to ask me anything about it.


r/C_Programming • • 3d ago

cc_task: write C coroutines with async/await and closure

Thumbnail
github.com
4 Upvotes

Just like js and C#, but this is C, with closure. Also very lightweight, small enough to fit in a CPU cache line.

#include "cc_task.h"
#include <stdio.h>

int main(void)
{
    int c = 10; // task_b captures c and uses it as task state
    cc_task_t *task_b = cc_task_new(CC_TASK(t)
    {
        CC_BEGIN(t);
        printf("B: c = %d\n", ++$(c));
        CC_YIELD(t);
        printf("B: c = %d\n", ++$(c));
        CC_END(t, c);
    });

    cc_task_t *task_a = cc_task_new(CC_TASK(t)
    {
        CC_BEGIN(t);
        printf("A: await B ...\n");

        cc_uintptr code;
        CC_AWAIT(t, task_b, code);
        printf("A: B end, code = %llu\n", (unsigned long long)code);
        CC_END(t);
    });

    c = 0; // modifying c does not change the copy captured by task_b
    cc_task_t *t = task_a;
    cc_tr_e ret;
    do
    {
        ret = cc_task_resume(&t);
    }
    while (ret != cc_tr_end);

    return 0;
}

r/C_Programming • • 4d ago

Coding Dragon Curve fractal using C

Thumbnail
youtube.com
43 Upvotes

In this video, I code a Dragon Curve fractal using C and Raylib.

The approach is quite simple:

I take the last point as a pivot, then rotate the remaining points 90 degrees around it. Finally, I connect the new points to create the next iteration of the fractal.

Source code:
https://github.com/FractalCodeRicardo/zen-programming/tree/main/dragon-curve

#include <stdio.h>
#include <raylib.h>
#include <raymath.h>

#define linesSize 90000
#define lineSize 2

typedef struct {
  Vector2 p1;
  Vector2 p2;
} Line;

void DrawLines(Line lines[], int s) {
  for(int i = 0; i < s; i++) {
    Line l = lines[i];
    DrawLine(l.p1.x, l.p1.y, l.p2.x, l.p2.y, WHITE);
  }
}

Vector2 rotate(Vector2 p, Vector2 rp) {
  Vector2 d = Vector2Subtract(p, rp);
  Vector2 r = Vector2Add(rp, (Vector2) {-d.y, d.x});

  return r;
}

int AddLines(Line lines[], int s) {
  if (s * 2 >= linesSize)
    return s;

  Vector2 rp = lines[s-1].p2;
  int newSize = s - 1;
  for(int i = s -1; i >= 0; i--) {
    Line l = lines[i];

    Vector2 p1 = rotate(l.p1, rp);
    Vector2 p2 = rotate(l.p2, rp);

    newSize++;
    lines[newSize] = (Line) { p2, p1};

  }
  return newSize + 1;
}


int main() {

  Line lines[linesSize];
  int s = 1;
  float center = 900 / 2.0;

  lines[0] = (Line) {
    (Vector2) { center, center}, 
    (Vector2) { center + lineSize, center}, 
  };

  InitWindow(1500, 900, "Dragon curve");

  while(!WindowShouldClose()) {
    BeginDrawing();
    ClearBackground(BLACK);
    
    if (IsKeyPressed(KEY_SPACE)) {
      s = AddLines(lines, s);
    }

    DrawLines(lines, s);
    EndDrawing();
  }

  CloseWindow();
}

AI Disclaimer:
No AI was used.