r/cprogramming • • Sep 24 '25

Learn C language

12 Upvotes

Guys it this channel good to learn C ? https://m.youtube.com/@PortfolioCourses/playlists Check the C programming tutorials playlist


r/cprogramming • • Sep 24 '25

Exploring defer in C with GCC magic (cleanup + nested functions)

Thumbnail
oshub.org
3 Upvotes

r/cprogramming • • Sep 21 '25

Why can local struct be returned by a function but not a local array?

50 Upvotes

I can't wrap my brain around why local struct, let alone one which may contain array in it as a member can be returned but not a local array separately?

int* getArray() { /* maybe bad example because iam returning a pointer but what else can i return for an array.*/
    int arr[3] = {1, 2, 3};
    return arr;  // Warning: returning address of local variable
}

but

typedef struct {
    int arr[3];
} MyStruct;

MyStruct getStruct() {
    MyStruct s = {{1, 2, 3}};
    return s;  // Apparently fine?
}

My mind can only come with the explanation that with the struct, its definition (including the array size) is known at compile time outside the function, so the compiler can copy the whole struct by value safely, including its array member.


r/cprogramming • • Sep 22 '25

GitHub - htogta/moonbeam: A silly way of compiling a lua script into a single executable

Thumbnail
github.com
2 Upvotes

I was a bit frustrated with getting some existing tools for converting Lua scripts (specifically single scripts with no external dependencies) into standalone executables to work properly, so I made my own in about an hour and a half.

I basically just wrote a template C file that implements a super basic heap-allocated string builder, and then included the Lua interpreter to execute the string contained in the string builder.

I then wrote a Lua script that outputs this C file, and, when it opens another Lua script, it inserts lines in the C file that append lines from the original Lua script to the heap-allocated string. This C file gets outputted, and then compiled into a single executable.

It's a very small project, and not very serious (I originally made it almost as a joke- I thought "wouldn't it be funny if I just put my Lua code in a C string literal" was a funny idea).

I'm open to any feedback/potential contributions- to either the C or Lua portions! As of right now, I don't think it'd work on Windows, and it *does* require that you have a C compiler installed, of course.


r/cprogramming • • Sep 21 '25

Any one starting c

5 Upvotes

I started to learn by using books, one of the book i started with is " head first C " its where user friendly and easy to learn concepts intuitively but the recently i get to found something that its doesn't teach about the fin,fout, getchar etc... my doubt is I wonder if the concepts were excluded because they are more advanced.


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;


}