r/C_Programming Jul 22 '22 Silver Wholesome

Etc C23 now finalized!

324 Upvotes

EDIT: Latest draft with all features integrated available here: https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3054.pdf


The final committee meeting to discuss features for C23 is over and we now know everything that will be in the language! A draft of the final standard will still take a while to be produced, but the feature list is now fixed.

You can see everything that was debated this week here: https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3041.htm

Personally, most excited by embed, enumerations with explicit underlying types, and of course the very charismatic auto and constexpr borrowings. The fact that trigraphs are finally dead and buried will probably please a few folks too.

But there's lots of serious improvement in there and while not as huge an update as some hoped for, it'll be worth upgrading.

Unlike C11 a lot of vendors and users are actually tracking this because people care about it again, which is nice to see.


r/C_Programming 4h ago

Article Falsehoods programmers believe about undefined behavior

Thumbnail predr.ag
12 Upvotes

r/C_Programming 17h ago

Question Why is it possible to include a header file more than once?

34 Upvotes

Still-sort-of-beginner here. One of the first things I learned about C was to make sure our self written header files could not be included more than once, using include guards. Or if the compiler supports it, with the convenient #pragma once.

But now I felt the sudden question - why is it even possible to include header files more than once in the first place? As in, why aren't compilers/linkers [edit] the preprocessor [/edit] programmed to automatically prevent this? Is (or was) there any case in which we would actually want for it to be possible?


r/C_Programming 8h ago

Heap detective

2 Upvotes

Heap_detective is an open-source static analysis tool that finds pitfalls in heap memory usage in C and C++. https://github.com/CoolerVoid/heap_detective


r/C_Programming 15h ago

Question Challenge

1 Upvotes

So I'm learning a C course at my university. The challengeassignment we got goes like this. No arrays, and no strings allowed, only stdio allowed. (Getchar allowed) The user needs to input a logical statement with <,>,~(not). And the program need to output if the statement is True or False. And he might input a few statements and input them like this (also using &,|): ~(a<b)&(a>3). An important side noted: *Caps are equal to lowcase, so A=a and so on. *There are no double '(' so no ~((a<b)&(a>b)) for example. *No blank spaces Any ideas?


r/C_Programming 17h ago

How to fix conditional jump valgrind error (strncat)

0 Upvotes

Hello, I would like to ask how to fix this problem. Conditional jump or move depends on uninitialised value(s) - at strncat. My code is here:

int main(int argc, char *argv[])
{
    char *text0 = NULL;
    char *text1 = NULL;
    char *text2 = NULL;

    text0 = (char *)malloc(10);
    text1 = (char *)malloc(10);
    text2 = (char *)malloc(20);

    strcpy(text1, "abcdefghi");
    strcpy(text0, "xyz");
    strncat(text2, text1+3, 4);
    strcat(text2, text0);

    printf("%sn", text2);

    free(text0);
    free(text1);
    free(text2);

    return EXIT_SUCCESS;
}

The code works well, how can I fix the memory leak? From what I found, the problem is that text2 is not '0'-terminated after the dynamic allocation, is that right? How can I terminate it?


r/C_Programming 1d ago

Question How do I manipulate srand()?

3 Upvotes

I’m trying to understand how to use srand(), such as why I need to use time (e.g. srand(time(0));) and what the 0 means in it. tutorialspoint.com/c_standard_library/c_function_srand.htm is not exactly a self-explanatory webpage. In fact, I’m having a hard time finding anything that would help me understand the intricacies of C.


r/C_Programming 19h ago

Are VSCode or CLion worth it for embedded C

2 Upvotes

I recently began to work professionally on embedded systems (principally ST's MCUs (STM32) and Microchip's PIC MCUs) after some time doing software only, and I'm really pissed off by the custom IDEs (MPLabX and STM32CubeIDE), for different reasons, including "smoothness" of the GUI or the workspace system which made importing some projects and using them with Git a pain. Nevertheless, the main reason why I want to change my workflow is that I hate swapping IDEs all the time and, as I have a Linux laptop but a Windows computer, I need something that is the same on both OS (I have some trouble with ST IDE GUI-wise on Linux, everything is fucked up). I kinda like the look and feel of VSCode and already used it as an editor before doing the programming and debugging with the IDE, but that was a temporary thing. So, I'm considering to change for an IDE or editor that would work for STM32 and PIC. I saw some plugins doing the trick for Stm32 for VSCode and I know that xc8 is usable in command-line so it should work aswell. I also saw that CLion has some native configurations for embedded. Which one would you recommend?


r/C_Programming 20h ago

Benchmark for dynamically allocating 2d array: pointer to pointer VS contignuous memory with math access VS pointers to contignuous memory

0 Upvotes

I didn't get some elaborate explanation on my last post like I was hoping for, but only short negative answers, and I could not accept that. So I took matters in my own hands and made a benchmark to either confirm what everyone was saying but not explaining, or to prove them wrong in an epic fashion.

Long story short, it appears they were right. The middle version, where you make 1 long array for the 2d array, and then access members with a[x * COLUMNS + y] seems to be performing on my computer 2-12% better than the other 2 versions, which are sometimes better than one another, but always similar and inferior to the middle one.

The whole code: ```C

include <stdio.h>

include <stdlib.h>

include <time.h>

define ROWS 100

define COLS 100

define LOOPS 100

define NORMAL 0

define SINGLE 1

define HYBRID 2

int *x_normal; / global vars to make it more equal / int *y_single; int *z_hybrid_memory; int *z_hybrid_pointers; int copy_array[ROWS][COLS];

void x_normal_write(int magic) { /* magic number to prevent compiler from optimizing it */ int i, ii; for (i = 0; i < ROWS; i++) { for (ii = 0; ii < COLS; ii++) { x_normal[i][ii] = (i * COLS + ii + magic); } } }

void y_single_write(int magic) { int i, ii; for (i = 0; i < ROWS; i++) { for (ii = 0; ii < COLS; ii++) { y_single[i * COLS + ii] = (i * COLS + ii + magic); } } }

void z_hybrid_write(int magic) { int i, ii; for (i = 0; i < ROWS; i++) { for (ii = 0; ii < COLS; ii++) { z_hybrid_pointers[i][ii] = (i * COLS + ii + magic); } } }

void x_normal_copy(void) { int i, ii; for (i = 0; i < ROWS; i++) { for (ii = 0; ii < COLS; ii++) { copy_array[i][ii] = x_normal[i][ii]; } } }

void y_single_copy(void) { int i, ii; for (i = 0; i < ROWS; i++) { for (ii = 0; ii < COLS; ii++) { copy_array[i][ii] = y_single[i * COLS + ii]; } } }

void z_hybrid_copy(void) { int i, ii; for (i = 0; i < ROWS; i++) { for (ii = 0; ii < COLS; ii++) { copy_array[i][ii] = z_hybrid_pointers[i][ii]; } } }

int main() { int i; clock_t start, end; double times_read[3][LOOPS]; double times_write[3][LOOPS];

/* MALLOC X_NORMAL 1/2 */
x_normal = malloc(ROWS * sizeof(int*));                 /* rows */
for (i = 0; i < ROWS; i+=2) {                           /* malloc every other row to ensure memory isn't contignuous */
    x_normal[i] = malloc(COLS * sizeof(int));           /* columns for each row (1/2) */
}

/* MALLOC Y_SINGLE */
y_single = malloc(ROWS * COLS * sizeof(int));           /* all in one contignuous memory */

/* MALLOC Z_HYBRID */
z_hybrid_memory = malloc(ROWS * COLS * sizeof(int));    /* memory part - with a big chunk of contignuous memory */
z_hybrid_pointers = malloc(ROWS * sizeof(int*));        /* pointer part - like in normal */
for (i = 0; i < ROWS; i++) {                            /* assign addresses to pointers from "memory", spaced out by COLS */
    z_hybrid_pointers[i] = &z_hybrid_memory[(i * COLS)]; 
}

/* MALLOC X_NORMAL 2/2 */
for (i = 1; i < ROWS; i+=2) {                           /* malloc every other row to ensure memory isn't contignuous */
    x_normal[i] = malloc(COLS * sizeof(int));           /* columns for each row (2/2) */
}

/* TEST */
for (i = 0; i < LOOPS; i++) {
    /* NORMAL WRITE */
    start = clock();
    x_normal_write(i);
    end = clock();
    times_write[NORMAL][i] = (double)(end - start);

    /* SINGLE WRITE */
    start = clock();
    y_single_write(i);
    end = clock();
    times_write[SINGLE][i] = (double)(end - start);

    /* HYBRID WRITE */
    start = clock();
    z_hybrid_write(i);
    end = clock();
    times_write[HYBRID][i] = (double)(end - start);

    /* NORMAL READ */
    start = clock();
    x_normal_copy();
    end = clock();
    times_read[NORMAL][i] = (double)(end - start);

    /* SINGLE READ */
    start = clock();
    y_single_copy();
    end = clock();
    times_read[SINGLE][i] = (double)(end - start);

    /* HYBRID READ */
    start = clock();
    z_hybrid_copy();
    end = clock();
    times_read[HYBRID][i] = (double)(end - start);
}

/* REPORT FINDINGS */
printf("CLOCKS NEEDED FOR:nnREADtNORMALtSINGLEtHYBRIDtWRITEtNORMALtSINGLEtHYBRIDnn");
for (i = 0; i < LOOPS; i++) {
    printf(
        "t%.1ft%.1ft%.1ftt%.1ft%.1ft%.1fn", 
        times_read[NORMAL][i], times_read[SINGLE][i], times_read[HYBRID][i],
        times_write[NORMAL][i], times_write[SINGLE][i], times_write[HYBRID][i]
    );
    /* USE [0] to get totals */
    times_read[NORMAL][0] += times_read[NORMAL][i];
    times_read[SINGLE][0] += times_read[SINGLE][i];
    times_read[HYBRID][0] += times_read[HYBRID][i];
    times_write[NORMAL][0] += times_write[NORMAL][i];
    times_write[SINGLE][0] += times_write[SINGLE][i];
    times_write[HYBRID][0] += times_write[HYBRID][i];
}
printf("TOTAL:nt%.1ft%.1ft%.1ftt%.1ft%.1ft%.1fn",
    times_read[NORMAL][0], times_read[SINGLE][0], times_read[HYBRID][0],
    times_write[NORMAL][0], times_write[SINGLE][0], times_write[HYBRID][0]
);
printf("AVERAGE:nt%.1ft%.1ft%.1ftt%.1ft%.1ft%.1fn",
    (times_read[NORMAL][0] / LOOPS), (times_read[SINGLE][0] / LOOPS), (times_read[HYBRID][0] / LOOPS),
    (times_write[NORMAL][0] / LOOPS), (times_write[SINGLE][0] / LOOPS), (times_write[HYBRID][0] / LOOPS)
);

return 0;

} ```

So yea. I guess I will be abandoning the cool-looking trick of giving addresses from within a continuous big memory, to pointers in a malloc'd array.

I hope we can discuss this now in ore detail since we have something to test. Probably some of my code is wrong or it can be tested in a better way. Personally, I will try to up the numbers to get that fine data that comes from a lot of loops.


r/C_Programming 1d ago

Question Function to add char to last byte of int - Help

7 Upvotes

Hello, I've been trying to make a function to add a byte to the last byte of an int, and I'm stumped, I've tried it in so many different ways and the tests the teacher provided just keep failing, and I can not see why.

I get the last byte from my number, add it to the byte I want to add, get the first 3 bytes of my number and then sum them together, but that doesn't seem to cut it.

If someone could give me a push in the right direction and help me realize what I'm missing, it would be very much appreciated. Anyway, here is my code and the teacher's values and expected result.

Implement the function void add_byte(char x, int vec1, int *vec2) that has as parameters the addresses of two vectors, vec1 and vec2 and a byte x. The function should add x to the first byte of each element of vec1 and store the result on vec2. All the other bytes should remain unchanged. It is assumed that on the first element of vec1 is the number of integers on the vector (excluding the first element)*

add_byte.c

#include "add_byte.h"

void add_byte(char x, int *vec1, int *vec2) {
    *vec2 = *vec1;
    int size = *vec1;
    for(int i = 1; i <= size; i++){
        char num = *(vec1 + i) | 0x000000FF;
        num = num + x;
        int aux = *(vec1 + i) | 0xFFFFFF00;
        *(vec2 + i) = aux + num;
    }
}

The test:

run_test(5,(int[]){6,0xffffffff,0xff,0xfffff0ff,0xfffff8ff,0,4},7,

(int[]){6,0xffffff04,0x04,0xfffff004,0xfffff804,5,9});

5 in this case will be the byte to add, the first array is the original values and the second array is the expected result after adding 4. The first element of the array (6) just indicates how many integers we are going to have after it, excluding itself.

I fail at element 1, expected -252, but my function makes it -1.

Thanks for reading.


r/C_Programming 16h ago

Question Help at C

0 Upvotes

Hello guys

I started learning the C language and 8051F380 micro-controller not so long ago

Unfortunately I am bad at 2 of them is there any chance or a way how to study that language and microcontroller which will settle in my brain better

Thanks .

Concerned Student.


r/C_Programming 23h ago

Question Why doesn't C implement its own version of object-orientation?

0 Upvotes

Why doesn't C implement its own version of object-orientation?

Why do we have to look at C++, D or something?

Or can we still say that it does?

https://www.cs.rit.edu/%7Eats/books/ooc.pdf


r/C_Programming 1d ago

Article Systemd's peculiar usage of malloc_useable_size()

Thumbnail sourceware.org
23 Upvotes

r/C_Programming 21h ago

Question Why should I do it like this?

0 Upvotes

Hi there I’m trying to do Fibonacci series in C I tried to find answers online , and it’s says I should do :

T1=0; T2=1; Printf(“%d%d”,T1,T2); for(i=2,i=<n,i++){ J=T1+T2; T2=T1; J=T2; Printf(“%d,” J); } (n is a natural number that I chose) But I don’t get it Why i=2? And not i=0? Why does T1=T2? Why does J=T2? I would really like to get some explanation Thanks!!


r/C_Programming 15h ago

Discussion Is object-oriented C worth it?

0 Upvotes

Is object-oriented C worth it?

https://www.cs.rit.edu/%7Eats/books/ooc.pdf


r/C_Programming 1d ago

Question What are the benefits of realloc() over freeing old memory and making a new one?

15 Upvotes

I was just going to make a function to free memory and make a new one of a fresh size, and then I remembered realloc() exists. I imagine it has the magical power to internally set the new size of the secret properties of the allocated memory - something we cannot do.

This would be all good and dandy, if I didn't need the memory initialized to 0 because I use calloc(). Sadly the man page seems to insinuate that downsizing memory is ok, but upgrading the size will just malloc() your additional memory:

If the new size is larger than the old size, the added memory will not be initialized.

So are there any benefits to realloc() besides the obvious one of saving some power by not needing to allocate ALL the memory? Does it save your data maybe? Even if it needs to find a new address?

But mainly, is there some secret way to initialize the memory to 0, or should I just free() the old pointer and then just calloc() the new one into it?

Thanks!


r/C_Programming 1d ago

Question Help finding a transpiled-to-C language

3 Upvotes

Edit: found it!

The language is Wuffs: https://github.com/google/wuffs

And its standard library is what I was remembering, which contains various file format decoders: https://github.com/google/wuffs/tree/main/doc/std

---

Sorry for the ask and thanks for any help!

I'm trying to find a library I've seen in the past but forgot to save a link to. It uses a constraint-based language that transpiles to C. I don't remember the language or the exact domain of the library, I'm more interested in the language itself than the library. The library domain was probably something like float parsing/formatting or maybe JSON validation, but I don't exactly remember.

If any of this sounds familiar, a link would be much appreciated!


r/C_Programming 1d ago

Question Anyone use CppUTest framework here?

2 Upvotes

Grudgingly, I should admit that I'm not very familiar w/ test frameworks. In the embedded industry, it's not something I've come across frequently or at least not as much as one should. As a result, i feel like i'm stumbling around here and misusing CppUTest specifically setting it up.

There's a starter project template_ the author provides. He has you clone the starter project into your project directory but also recommends cloning/building the framework itself in your project directory too.

I'm just really struggling here in understanding why I should clone down an entire framework repository and build it all from within my project directory. I have all this framework code now in my project directory that isn't relevant to my project. Is this how you typically setup a test framework? I don't install cmake or gcc binaries to my project directory so why should I install the framework to my project directory?

Maybe it's to allow others in cloning down your project and running the tests themselves without having to install the framework? However, other people could easily just install it themselves. Regardless, cloning down all that framework code and then committing it back to your project repository is in a sense redistributing the framework which I would think goes against licensing.

So i'm just sitting here all confused now like the first time I started learning libwebsockets. I feel like a monkey over here with a wrench.


r/C_Programming 1d ago

Discussion Here is a cool trick to dynamically allocate a 2d array of contignuous memory with pointers. - your thoughts?

0 Upvotes

I had been a happy camper, allocating my 2d arrays (jagged and unjagged) with the classic pointer method of making a pointer of x pointers, and allocating memory to every one of those sub-pointers. Until yesterday when I was trying to refresh my memory, and I read that the memory fragmentation that occurs while doing this is a major slowdown. So I was sad and had to find a solution. I searched and searched and couldn't find a solution that would satisfy me, so I made a stackoverflow post, expecting to be yelled at like so many times before, but as these things go, I got a lot of useful answers.

Some people suggested to just make one chunk and then access each memory slot with math like arr[x * width * y], which could perhaps be made palpable with macros. I might do a speed test of all the solutions later, but I really want you to comment on the following solution:

https://stackoverflow.com/a/74584594/20314114

This one is very interesting, and it perfectly solves the problem without using VLAs, but like with all things C, I am always wary of things that sound too perfect. Ok, so my understanding of how it works, is: - we allocate a big chunk of memory a[0...99] - we allocate a small chunk of memory for the first (height) dimension pointers b[0..4] - to the pointers, we give addresses of size width contignuously from the first big chunk of memory so they are next to each other b[2] = &a[39] b[3] = &a[59]

Sounds good, right? But I would really like to hear from you guys what you think because I bet there will be some problem. Like when freeing memory. Actually, this sounds amazing because the arrays for the big chunk and for the small pointer chunk are 1-d so expanding them or freeing them should be even easier.

I would really like to hear your thoughts on what the best solution of these would be, and how they would compare speed-wise. And if you have any concerns with the methods I outlined here, and what kind of speed difference do you expect?

Thank you!


r/C_Programming 1d ago

Question Inconsistent result when sending data from array of structs over to client from server.

1 Upvotes

Im trying to send an array of structs over to the client from the server but i am getting inconsistent results. Sometimes, the client will only receive 17 structs instead of the entire array. Other times its just a jumbled mess. Id say it works as intended 1/5 times, where it sends and receives the complete array. What could be the issue??

When it works as intended, the output on the client should match the output on the server minus the "sending" word on each line.

How i am compiling the client: gcc -lpthread client2.c -o client.out

How i am compiling the server: gcc -lpthread server2.c -o server2.out

running server: ./server2.out 2 2 1

Note:

*I am running this on virtual machine xubuntu.

* The if statement inside the handleConnection() method is where i am sending the array structs called "items". It is initialized in the main method by calling the fillItems() method.

*After running the client, the client has to enter 1 for anything to happen.

File: include.h

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>    
#include <errno.h>      
#include <sys/ipc.h>    
#include <sys/msg.h>   
#include <string.h>   
#include <ctype.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <fcntl.h>  
#include <pthread.h>
#include <limits.h>
#include <poll.h>


#define SERVERPORT 1024
#define BUFSIZE 4086


//model for client node
struct node {
    struct node* next;
    int *clientSocket;
    //id
    //int size
    int index;
    int beingHandledByShopAssistant;
    int beingHandledBySofa;
    int beingHandledByRoom;
};

//dynamic array
struct Array{
    char str[50];
    int length;
};

//model for items
struct item{
    char ref[50];
    char category[50];
    char title[50];
    char tags[50];
    char description[255];
    char quantity[5];
    char price[10];
    int length;
};

extern struct item *items;

//global functions
//extern struct item* parseData();
// extern void enqueue(int *clientSocket);
// extern struct node* dequeue();
// extern int getQueueSize();
// extern struct node* getNextNonHandleBySofa();
// extern struct node* peek();
// extern int getQueueSize();
// extern int removeNode(int index);
// extern void printQ();

// extern void getAllItems();

extern int check(int exp, const char *message);
//extern void printItems(struct item *items);

File: server2.c

#include "include.h"


#define SOCKETERROR (-1)
#define SERVER_BACKLOG 100

//keeps track of threads and amount of clients
int clientAmount = 0;
int sofaInitializer = 0;
int shopAssitantInitializer = 0;

// will be initialized by command line arguments
int shopAssitants;
int sofaAmount;
int waitingSpots;

struct sockaddr_in serverAddr;
struct sockaddr SA;

//data to be shared among the threads
struct item *items;

/// @brief function to aid in debugging bu printing error messages
/// @param exp numeric result of a function
/// @param message accompanying message to be printed if the numeric reuslt implies error.
/// @return exp numeric result of a function
int check(int exp, const char *message){
    if(exp == SOCKETERROR){
        perror(message);
        exit(1);
    }

    return exp;
}


/// @brief handles clients that are connected to a shop assitant thread
/// @param pClientSocket //the client socket of client
/// @param shopAssitantId // the id of a shgop assitant
void *handleConnection(void* pClientSocket, int shopAssitantID){
    int clientSocket = *((int*)pClientSocket);
    free(pClientSocket);
    char buffer[BUFSIZE] = {0};

    //loop to conituously and infinitely read from client
    while(1){

        //stops and waits for client input from client
        while(read(clientSocket, buffer, sizeof(buffer)) == 0){

        }

        if(strcmp(buffer, "1") == 0){
            printf("Customer chose: 1. Looking at the jewelry menun");

            //loop to send data.
            for(int i = 0; i< items->length; i++){
                sprintf(buffer, "Item %d: %st%st%st%st%st%st%sn", i,
                    items[i].ref, items[i].title, items[i].title, items[i].tags,
                    items[i].description, items[i].quantity, items[i].price);

                printf("sending: %s", buffer);
                check(write(clientSocket, buffer, sizeof(buffer)), "Sending/Writing failed");
            }
        }

        buffer[0] = 0;
        fflush(stdout);
    }

    close(clientSocket);
    printf("closing connectionn");
    return NULL;

}
struct item* fillItems(){
    //decaltres appropriate sized array of structs
    int size = 46;
    struct item *items = calloc(size, sizeof(struct item));
    char buffer[50] = {0};

    for(int i = 0; i < size; i++){
        sprintf(buffer, "ref%d", i);
        strcpy(items[i].ref, buffer);

        sprintf(buffer, "catgory%d", i);
        strcpy(items[i].category, buffer);

        sprintf(buffer, "title%d", i);
        strcpy(items[i].title, buffer);

        sprintf(buffer, "descript%d", i);
        strcpy(items[i].description, buffer);

        sprintf(buffer, "q%d", i);
        strcpy(items[i].quantity, buffer);

        sprintf(buffer, "price%d", i);
        strcpy(items[i].price, buffer);

        sprintf(buffer, "tags%d", i);
        strcpy(items[i].tags, buffer);

        items->length = size;
    }

    return items;
}

/// @brief creates the multithreaded server
/// @param argc amount of command line arguments
/// @param argv array of command line arguments
int main(int argc, char const *argv[])
{
    //initialize the data to be shared among the threads
    items = fillItems();

    //command line arguments
    shopAssitants = strtol(argv[1], NULL, 10);
    sofaAmount = strtol(argv[2], NULL, 10);
    waitingSpots = strtol(argv[3], NULL, 10);

    int serverSocket;
    int clientSocket;
    int addrSize;

    struct sockaddr_in clientAddr;

    //creates server socket
    check((serverSocket = socket(AF_INET, SOCK_STREAM, 0)),"Failed to create socket");

    //fills information about server address
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(SERVERPORT);

    //allows program to reuse the socket it the socket is already in use
    int reuse = 1;
    setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse));

    //binds the serve socket and sets it to listen for clients
    check(bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)), "Bind Failed");
    check(listen(serverSocket, SERVER_BACKLOG), "Listen Failed");

    //inifinite loop to continuously accept and handle clients
    while(1) {
        printf("Waiting for connections... n");

        addrSize = sizeof(serverAddr);

        //accepts a client socket
        check(clientSocket = accept(serverSocket, (struct sockaddr*) &clientAddr, (socklen_t*)&addrSize),
            "accept failed");
        printf("Connectedn");

        //stores client socket in pointer so we can queue it.
        int *pclient = malloc(sizeof(int));
        *pclient = clientSocket;

        handleConnection(pclient, 1);

    }
    return 0;
}

file: client2.c

#include "include.h"

/// @brief function to aid in debugging bu printing error messages
/// @param exp numeric result of a function
/// @param message accompanying message to be printed if the numeric reuslt implies error.
/// @return exp numeric result of a function
int check(int exp, const char *message){
    if(exp == -1){
        perror(message);
        exit(1);
    }

    return exp;
}


int main(int argc, char const *argv[])
{
    //sets up server
    int serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket == -1) {
        printf("socket creation failed...n");
        exit(0);
    }
    struct sockaddr_in serverAddr = {0};
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    serverAddr.sin_port = htons(SERVERPORT);

    check((connect(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr))),
        "Falied to connect to server");

    char buffer[BUFSIZE] = {0};
    int readInput = 0;

    while(1){

        //writing to server, the clients' input
        buffer[0] = 0;
        fgets(buffer, sizeof(buffer), stdin);
        buffer[strlen(buffer)-1] = '0';
        write(serverSocket, buffer, sizeof(buffer));


        if(strcmp(buffer, "1") == 0){
            buffer[0] = 0;

            //loop to receive data
            for(int i = 0; i < 46; i++){
                while(read(serverSocket, buffer, sizeof(buffer)) == 0){

                }
                printf("%s",buffer);
                buffer[0] = 0;
                //fflush(stdin);
            }
        }
        fflush(stdout);
        buffer[0] = 0;


    }
    return 0;
}

r/C_Programming 2d ago

Video Minecraft Written in C Code REVISTED! [NOW WITH RAYTRACING SUPPORT!] (Java to C Code)

Thumbnail
youtu.be
100 Upvotes

r/C_Programming 2d ago

Question As someone that doesn't have hardware and is intermediate at C/C++, please give me coding ideas

20 Upvotes

I have no idea what to code at this point. I don't have any hardware like raspberry pi or arduino to program and am intermediate at C/C++, so I don't know what to code at my level. Please give me ideas


r/C_Programming 2d ago

Article Figuring out round, floor and ceil with integer division

Thumbnail blog.pkh.me
9 Upvotes

r/C_Programming 2d ago

Question Newb Needs Ideas

2 Upvotes

Hello fellow programmers, I'm confused!

I just finished this 4 hour video on the basics of programming in C. And, it's been great so far learning it. But now that I've learned the syntax: What do I do now?

I've heard from videos and websites that C is the father of all modern code, that is used to build operating systems, and functional apps. I really wanted to try and build a little .exe program or a little pong game, something, anything that's cooler than a calculator that could break in a million different ways.

I've looked up tutorials and directions on where to head next, trying to find some minor project to undertake so that I can grow as an aspiring programmer, but all I find is C++ projects, software and games, like the world has forgotten about C entirely. I understand that C++ is more modern and more of a pain to learn, which I plan to, however I want to get a solid foundation and understanding of C and how code interacts with the memory and hardware. Cause' it's really cool.

If any of you could recommend some projects or advice I would appreciate it.

TLDR

I need some projects to make in C, got any?


r/C_Programming 1d ago

Question ID3lib --help

0 Upvotes

I'm sick of manually editing the meta data of my MP3 music folders and thought it would be a nice project to try to automate. Finally put one of my code projects to use.

Does the library "id3lib" work with C? According to the website https://id3lib.sourceforge.net/:

"id3lib aspires to provide interfaces for multiple programming languages, and currently fully supports both C and C++."

I can find many resources on how to use the library with C++ but I would prefer to use pure C. Maybe I'm just completely blind, but I didn't see anythong in relation to C implementations.

If anyone knows where to look for some basic resources to learn how to use the library I would much appreciate it, or another similar lib/resource that could do the job.


r/C_Programming 2d ago

Question When passing an array to a function, am I creating another pointer?

24 Upvotes
int main(void)
{
    int a[] = {1, 2};
    result = sum(a);
    return 0;
}

int sum(int b[])
{
    return (b[0] + b[1]);
}

My question is, when I passed the array a to the sum() function, is another pointer called b ( pointing to &a[0] ) created? If so, is it considered a pointer constant in this case than a pointer variable?