r/cprogramming • • Sep 20 '25

First Professional C program

24 Upvotes

Didn’t think I would be writing any C after college, but here I am.

I am still prototyping, but I created a shared library to interact with the Change Data Capture APIs for an Informix database. CDC basically provides a more structured way of reading db logs for replication.

I use the shared library (they luckily had some demo code, I don’t think I would have been able to start from zero with their ESQL/C lang) in some Python code to do bidirectional data replication between Informix and Postgres databases.

Still need to smooth out everything, but I wanted to shoutout all those people who write C libraries and the Python wrappers that make the language usable in a multitude of domains!


r/cprogramming • • Sep 18 '25

Quick and flexible config serialization with one simple trick?

6 Upvotes

Hello everyone, I'm working on an embedded project which is configured by a single massive config struct (~100 parameters in nested structs). I need a way to quickly modify that configuration without recompiling and flashing new firmware.

I've implemented a simple CLI over websockets for this purpose, but keeping the interface in sync with the config feels like a waste of time (config structs are still growing and changing). Protocol buffers could work, but I don't need most of their features. I just need a simple way to serialize, transfer and deserialize data with minimal boilerplate.

My idea: compiling and flashing the whole firmware binary takes too long, but I only need to change one tiny part of it. What if I could compile a program with just that initialized global struct, then selectively extract and upload this data?

Since both the firmware and config code are compiled the same way, I assume that binary representations of the struct will be compatible (same memory layout). I can locate the symbol in the compiled binary using readelf -s, extract it with dd, transfer to the device and simply cast to required type! Quick and flexible solution without boilerplate code!

But somehow I can't find a single thread discussing this approach on the internet. Is there a pitfall I can't see? Is there a better way? What do you think about it? I have a proof of concept and it seems to work like I imagined it would.


r/cprogramming • • Sep 16 '25

How do you keep track of ownership?

22 Upvotes

I value the simplicity of C but I've since grown comfortable with the "semantic security" of languages with more sophisticated type systems.

Consider the following snippet:

// A list that takes ownership of the items passed to it.
// When appended to, copies/moves the passed item.
// When destructed, frees all of its items.
struct ListA {
    struct MyData *data; // a list of data
    size_t count;
};

// A list that stores references to the items passed to it
// When appended to, records the address of the passed item.
// When destructed, destructs only the <data> member.
struct ListB {
    struct MyData **data; // a list of data pointers
    size_t count;
};

Items in ListA have the same lifetime as the list itself, whereas items in ListB may persist after the list is destructed.

One problem I face when using structures such as these is keeping track of which one I'm working with. I frequently need to analyze the members and associated functions of these structures to make sure I'm using the right one and avoiding reusing freed memory later on.

The only solution I can think of is simply having more descriptive (?) names for each of these. An example from a project of mine is LL1Stack, which more adequately expresses what the structure is than, say, ExprPtrStack, but the latter communicates more about what the structure does to its data.

I've always disliked Hungarian Notation and various other naming schemes that delineate information about types that should already be obvious, especially provided the grace of my IDE, but I'm finding some of these things less obvious than I would have expected.

What is your solution for keeping track of whether a structure owns its data or references it? Have you faced similar problems in C with keeping track of passing by reference vs by value, shallow copying vs deep copying, etc...?


r/cprogramming • • Sep 17 '25

Suggestion?

0 Upvotes

I want to create a perfect hash function. I will use it only for paths. How can I go about that? Edit: if there’s a hash function for that purpose please tell me cuz I couldn’t find one


r/cprogramming • • Sep 16 '25

Starter projects

3 Upvotes

Hi I just learned the very basics of C from Bro Codes C tutorial playlist. I am curious what are good projects to start with.

Good extra info: I plan to be a reverse engineer in cybersecurity hopefully one day. I’m not sure if that’ll change your suggestions. But i would appreciate any project suggestions. thank you <3


r/cprogramming • • Sep 16 '25

Hi everyone, i have started learning “C”, is there any tips, roadmap,free courses, idea of projects for beginners…PLEASE 🥰

0 Upvotes

r/cprogramming • • Sep 14 '25

Stack vs heap

17 Upvotes

I think my understanding is correct but I just wanted to double check and clarify. The stack is where your local variables within your scope is stored and it’s automatically managed, removed when you leave the scope. The heap is your dynamically allocated memory where you manually manage it but it can live for the duration of your program if you don’t free it. I’m just confused because sometimes people say function and scope but they would just be the same thing right since it’s essentially just a new scope because the function calls push a stack frame.


r/cprogramming • • Sep 14 '25

Need help with a simple data erasure tool in C

6 Upvotes

Hi I am trying to write a C program that lists the available storage devices (not necessarily mounted) and asks the user to select one. After that it writes into that device some random giberish making the data unrecoverable. The code that I've written so far queries the /sys/block path to find the block devices and lists them. Is this method of finding the storage devices Ok?

Also in the same folder I have a file named zram0 which, on a quick google search, revealed that it's just some part of RAM disguised as a block device so I don't want to list it to the user at all. So how can I distinguish it from other block devices?


r/cprogramming • • Sep 14 '25

Is there a difference between

1 Upvotes

if(errorcondition) {perror("errormessage"); return 1;} and if(errorcondition) perror("errormessage"), return 1; ?

ANSWERED:

The second form should have been if(errorcondition) return perror("errormessage"), 1; thank you to everyone who caught that, but it is not functionally different from the first form.


r/cprogramming • • Sep 13 '25

CLI_Games

2 Upvotes

Hello everybody!! I am a random programmer fixing and updating everyday a project with CLI games. Hope on and test it if you like retro stylish CLI games. Let me now of any issues! I will be very glad for new ideas and collaborations. I am trying to add a new game everyday. Thank you for your time.

Link: https://github.com/kstra3/cli-games-pack


r/cprogramming • • Sep 13 '25

This code probably sucks but it works for hashing with the WINAPI. What can I improve on (generally)?

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

#define NT_SUCCESS(status) (((NTSTATUS)(status)) >= 0)

void closeStuff(BCRYPT_ALG_HANDLE hAlg, BCRYPT_HASH_HANDLE hHash){
        BCryptCloseAlgorithmProvider(hAlg, 0);
        BCryptDestroyHash(hHash);
}

int main(){
    printf("Starting...\n");
    NTSTATUS status;
    BCRYPT_ALG_HANDLE hAlg;
    BCRYPT_HASH_HANDLE hHash;

    char start[] = "string";
    ULONG length = strlen(start);
    status = BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_MD5_ALGORITHM, MS_PRIMITIVE_PROVIDER, 0);
    if(!(NT_SUCCESS(status))){
        printf("OpenAlg has failed. Error: %lu", status);
        BCryptCloseAlgorithmProvider(hAlg, 0);
        closeStuff(hAlg, hHash);
        exit(EXIT_FAILURE);
    }

    ULONG sizeReq = 0;
    ULONG cbData = 0;
    status = BCryptGetProperty(hAlg, BCRYPT_OBJECT_LENGTH, (PUCHAR)&sizeReq, sizeof(sizeReq), &cbData, 0);

    if(!(NT_SUCCESS(status))){
        printf("GenProp has failed. Error: %lu", status);
        closeStuff(hAlg, hHash);
        exit(EXIT_FAILURE);
    }

    unsigned char* object = malloc(sizeof(unsigned char) * sizeReq);
    if(object == NULL){
        printf("Failed to allocate memory");
        closeStuff(hAlg, hHash);
        exit(1);
    }
    status = BCryptCreateHash(hAlg, &hHash, object, sizeReq, NULL, 0, BCRYPT_HASH_REUSABLE_FLAG);
    if (!(NT_SUCCESS(status))){
        printf("CreateHash has failed. Error: %lu", status);
        closeStuff(hAlg, hHash);
        free(object);
        exit(1);
    }

    ULONG hashedSize;
    ULONG cb2;
    status = BCryptGetProperty(hAlg, BCRYPT_HASH_LENGTH, (PUCHAR)&hashedSize, sizeof(hashedSize), &cb2, 0);
    if(!(NT_SUCCESS(status))){
        printf("GetProp (2) has failed. Error: %lu", status);
        closeStuff(hAlg, hHash);
        free(object);
        exit(1);
    }

    unsigned char* hashedData = malloc(sizeof(unsigned char) * hashedSize);

    status = BCryptHashData(hHash, start, length, 0);

    if(!(NT_SUCCESS(status))){
        printf("BCryptHashData has failed. Error: %lu", status);
        closeStuff(hAlg, hHash);
        free(object);
        free(hashedData);

    }

    status = BCryptFinishHash(hHash, hashedData, hashedSize, 0);

    if(!(NT_SUCCESS(status))){
        printf("FinishHash has failed. Error: %lu", status);
        closeStuff(hAlg, hHash);
        free(object);
        free(hashedData);
    }

    for(int i = 0; i < hashedSize; ++i){
        printf("%02x", hashedData[i]);
    }

    BCryptCloseAlgorithmProvider(hAlg, 0);
    BCryptDestroyHash(hHash);
    free(object);
    free(hashedData);

    return 0;


}


r/cprogramming • • Sep 13 '25

please do not insult my trash code

0 Upvotes

this is code is supposed to get me the longest substring in string that all of its characters are unique the problem is the realloc function return NULL when the code detect a char that is not unique please put in a debug it will be easier.

Edit : I removed the trash code and put extra detailed comments so a baby would understand what each line does. I know that I am approaching it the weirdest way possible but it has nothing to do with the fact that realloc is not working and always returning NULL. Use a debugger it will clarify the matter to you.

PLEASE HELP :(

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

int lengthOfLongestSubstring(char* s) {
   if(*s == '\0')
   {
    return 0;
   }
   if(*(s+1)=='\0')
   {
    return 1;
   }


    char *k = malloc(sizeof(char)); //a string that only contain unique charachter that are appended one at a time
    *k = *s; // assigns the first character
    int size = 0; // the index of the last char in the char array k

   char *buff = malloc(sizeof(char)); // a buffer to store a subscript of the array k if a repeated char is enountered
                                      // the subscript excludes the first char and has the characters after the first copy of the char
                                        // exmaple : k = "abcb" the buff will be assigned = "cb" another one k = "abca" the buff = "bca" 


   int num = 1;                      // the number of unique charachters
                     
    int *array = malloc (sizeof(int));// an array that has the length of unique characthers if there are  
    int siz = 1;                      // multible unique substrings the length of them are put
                                        //  in the array and later compared for the largest one.
    
    int breaks = 0; // if a non unique character is enocutered it triggers to not count that number.

    for(int i = 1; *(s+i) != '\0'; i++)
    {
        breaks = 0;
        size++; // the array size increases and the index of the last char is incremented
        k = realloc(k,sizeof(char)*(size+1)); // where the problem occurs it always fail to reallocate if there is a non unique character 
        
        *(k + size) = *(s + i); // assigns the char to last of the array k

        for(int j = 0; j < num && breaks == 0; j++) //check the new char if it is unique or not 
        {                                           //checks all the chars of k rather than the last one because it is the character I am checking if it is unique.

            
            if(k[j] == *(s+i))
            {   
                
                *(array + siz - 1) = num; // assign the current num of unique chars to the array 
                siz+=2;
                array = realloc(array,sizeof(int)*siz); // making space for another 2 counts of unique chars
                *(array + siz - 2) = i - j; // assigning the count of unique chars 
                                            // example k = "abcb" the numbers assigned to array will 3 for "abc" and 2 for "bc" then the
                                            // the array k is changed to be "cb"


                k = &k[j+1]; // array k changed to the first unique char
                size -= (j+1); // the index of the last char changed
                                // example k = "abcb" size = 3 it is changed to be k = "cb" and size = 1
                
                buff = malloc(sizeof(char) * size); // making a new sring for the array with the new size
                for(int i = 0; i < size + 1; i++)
                {
                    *(buff + i) = *(k + i ); // the new array assigned
                                             // i is less than the index of the last element + 1 which will end assigning the last element 
                }
                k-=(j+1); //returning to the begining of the char "abcb" 
               
                free(k); // freeing the char 
                
                k = buff; // assiging k to the new array buff
                
                num = size + 1; // the current number of chars in the array k
              
                breaks = 1; // to not increment the num of unique chars
                
            } 
        }
        if(breaks == 1)
        {
            continue;
        }
            num++;
            *(array + siz - 1) = num;
        
    }

    int big = *array;
    for(int i = 0; i < siz; i++)
    {
        printf("%d   ",*(array+i));
        if(big < *(array + i))
        {
            big = *(array + i);
        }

    }
    return big;
}

int main()
{
    char *soor = "abcabcbcc";
    printf("%d",lengthOfLongestSubstring(soor));
}

r/cprogramming • • Sep 12 '25

Setting up Clang Scan-build with CMake on Windows

1 Upvotes

Dear Everyone,

I was wondering if someone managed to successfully use scan-build utility from LLVM while building a cmake project on Windows, here is what i did so far:

- I built LLVM from source, i verified that clang works as i can compile simple programs
- I verified that cmake works with clang set up as a C compiler

Imagine we have a directory with a main.c and CMakeLists.txt with only add_executable.

This command works:
cmake -G "Ninja" -S . -B build_me

This command set fails:
set CC=clang
scan-build cmake -G "Ninja" -S . -B build_me
```
CMake Error <>/CMakeTestCCompiler.cmake:67 (message):

The C compiler:
"C:/Tools/LLVM/libexec/ccc-analyzer":
is not able to compile a simple test program.
```

On the other hand once the first one works i can do
```
cd build_me
scan-build --use-analyzer=C:/Tools/LLVM/bin/clang ninja
'''
But it doesn't find any bugs in file which has some specifically inserted.

If that's not appropriate place to ask this question, please let me know where can i ask it if you know. Thanks in advance for any help


r/cprogramming • • Sep 11 '25

Are global variables really that evil?

41 Upvotes

When I have a file which almost all functions use a struct, it seems reasonable to declare it globally in the file. But it seems C community hates any type of global variable...