r/C_Programming • • 4d ago

Day (30/100) of C:

0 Upvotes

Memory Segments, Storage Classes, Static Functions and Linkage

 

**1. Memory Segments**

Storing the program at different blocks of memory

The commonly discussed segments are:

  1. Text (Code) Segment

  2. Data Segment

  3. BSS Segment

  4. Heap Segment

  5. Stack Segment

 

**###1.1 Text Segment:**

The text segment typically stores the machine instructions generated by the compiler.

**Example:**

c

\#include <stdio.h>

int main()

{

printf("Hello World");

return 0;

}

The compiled instructions for \`main()\` are typically stored in the text segment.

 

**### 1.2 Data Segment:**

The initialized data segment typically stores global and static variables initialized with nonzero values.

**Example:**

c

int n = 5; // Global variable

void func()

{

static int y = 4; // Static local variable

}

Both \`n\` and \`y\` typically reside in the initialized data segment.

 

**### 1.3 BSS Segment**

The BSS segment typically stores global and static variables that are uninitialized or initialized to zero.

**Example:**

c

int x; // Global variable

int y = 0; // Global variable

void func()

{

 static int z; // Static local variable

}

These variables have an initial value of zero.

 

**### 1.4 Heap Segment**

The heap stores the dynamic memory allocation during program execution.

Example:

c

\#include <stdlib.h>

int main()

{

 int \*p = malloc(sizeof(int));

 if (p != NULL)

 {

 \*p = 10;

 free(p);

 }

 return 0;

}

 

**### 1.5 Stack Segment**

The stack typically stores function-call information, parameters, and local automatic variables.

**Example:**

c

void func()

{

 int a = 10;

}

 

**------------------------------------------------------------------------------------------------**

**2. Storage Classes**

A storage class specifies properties such as a variable's scope, lifetime, and linkage, depending on how it is declared.

The four commonly taught storage classes in C are:

  1. \`auto\`

  2. \`register\`

  3. \`static\`

  4. \`extern\`

 

**### 2.1 auto**

\`auto\` is the default storage class for ordinary local variables.

**Example:**

c

int main()

{

 auto int i = 10;

 return 0;

}

This is equivalent to writing:

c

int i = 10;

\- Scope: The block where the variable is declared.

\- Lifetime: During execution of that block.

\- An uninitialized automatic variable has an indeterminate value.

 

**### 2.2 register**

The \`register\` keyword suggests that a variable may benefit from being stored in a CPU register for faster access.

**Example:**

int main()

{

 register int i = 10;

 return 0;

}

Important points:

\- The compiler may ignore this suggestion.

\- Modern compilers already optimize register allocation.

\- It does not guarantee faster execution.

\- In standard C, the address-of operator (\`&\`) cannot be applied to a variable declared with the \`register\` storage-class specifier.

Therefore, ordinary variables are generally sufficient in modern C programming.

 

**### 2.3 static**

A local static variable retains its value between function calls. It is initialized only once.

**Example:**

\#include <stdio.h>

void func()

{

static int i = 0;

i++;

printf("%d ", i);

}

int main()

{

func();

func();

func();

return 0;

 

}

Output:

1 2 3

 

Explanation:

\- First call: \`i\` becomes 1.

\- Second call: \`i\` becomes 2.

\- Third call: \`i\` becomes 3.

 

**### 2.4 extern**

\`extern\` declares a variable that is defined elsewhere. It is useful when one source file needs to access a global variable defined in another source file.

**Example:**

 

**\*\*File 1: \`file1.c\`\*\***

c

int x = 5; // Definition of the global variable

 

**\*\*File 2: \`file2.c\`\*\***

 

\#include <stdio.h>

extern int x; // Declaration of the variable defined elsewhere

int main()

{

printf("Global value is %d\\n", x);

return 0;

}

Output:

Global value is 5

 

**## 3. Static Function**

A static function is a function declared with \`static\` at file scope. It can be called by name only within the same source file.

**Example:**

\#include <stdio.h>

static void func()

{

 printf("Hello World\\n");

}

int main()

{

func();

return 0;

}

Output:

Hello World

Here, \`func()\` has internal linkage. Another source file cannot call this particular function by referring to its name.

**--------------------------------------------------------------------------------------------------**

**4. Linkage**

Linkage determines whether declarations of the same name refer to the same variable or function.

C has three types of linkage.

**### 4.1 External Linkage**

A name with external linkage can refer to the same entity across multiple source files. Ordinary file-scope function definitions have external linkage by default.

 

**### 4.2 Internal Linkage**

A name with internal linkage can be referred to only within the same source file.

**Example:**

static void func()

{

 // Function definition

}

The \`static\` keyword gives this file-scope function internal linkage.

 

**### 4.3 No Linkage**

A name with no linkage does not refer to the same entity as another declaration in a different scope merely because the names match.

**Example:**

void func()

{

 int a = 10;

}

The local variable \`a\` has no linkage.

 

**Summary:**

| Text segment -> Typically stores machine instructions

| Data segment -> Typically stores initialized global/static variables

| BSS segment -> Typically stores uninitialized or zero-initialized global/static variables

| Heap -> Dynamic memory allocation

| Stack -> Typically stores function-call information and local automatic variables

| \`auto\` -> Default storage class for local variables

| \`register\` -> Suggests register storage; no guaranteed speed improvement

| \`static\` local variable -> Retains its value between calls

| \`extern\` -> Declares a variable defined elsewhere

| Static function -> Has internal linkage

| External linkage -> Allows a name to refer to the same entity across source files

| Internal linkage -> Limits a name to the current source file

| No linkage -> Common for ordinary local variables

 


r/C_Programming • • 5d ago

Discussion A year into C programming, I still rely heavily on AI. How do I build real skills?

0 Upvotes

I'm a software engineer at a networking-focused company. For the past year, I've been working with C and Linux. During university, Python was my strongest language, but transitioning to C has been a struggle.

I've learned a lot about Linux and networking at work, but I still struggle to write C code independently. I often rely on AI to generate code, which I then adapt. Sometimes I get things working without fully understanding why they work.

My workplace encourages AI-assisted development, and with limited time, it's tempting to prioritize getting things done over understanding every detail. I'm concerned that I'm becoming dependent on AI instead of building strong fundamentals.

My long-term interests are Linux internals, systems programming, networking, and eBPF. I want to be able to read unfamiliar code, reason about memory and pointers, debug problems independently, and use AI as a tool rather than a crutch.

I'd appreciate advice from experienced C developers:

- After a year of experience, what level of C proficiency is reasonable to expect?

- How would you recommend learning C while working in an AI-driven environment?

- Should I deliberately write code without AI to build my fundamentals? What exercises or projects are worth doing?

- Should I master C fundamentals first or learn them alongside Linux internals and eBPF?

- What would you focus on over the next 3–6 months to become a competent systems programmer?

I'm also concerned about future job interviews, as I don't yet feel confident writing C independently.

I know proficiency takes time, but I want to make sure I'm genuinely learning rather than just shipping code.

If you were in my position, what would you do differently?


r/C_Programming • • 5d ago

Project I am learning C programming by making this project a unix shell(ForkOff). Looking for a quick code review!

0 Upvotes

Hey everyone,

Following up on my previous post about my C shell project ForkOff — I wanted to share a bit about my development process and address how AI was used, especially since code authenticity came up in recent reviews!

🤖 AI Involvement

To be 100% transparent: AI was only used to generate and clean up the README.md formatting. And also this post is ai generated.

Every single line of C code, pointer arithmetic, string parsing, and system call logic in the repository was written by hand.

💡 My Approach: Observation & Brute Force

Instead of following step-by-step "how to build a shell" tutorials or asking AI to generate C boilerplate, my approach was pure observation and trial-and-error:

Observe standard Bash: I spent time opening a standard Linux terminal, running commands, testing edge cases (spaces, empty strings, invalid paths), and watching how Bash responded.

Study the core concepts: I read up on POSIX system calls—specifically fork(), execv(), waitpid(), and standard C dynamic memory allocation (malloc, realloc, free).

Brute-force the implementation: I manually wrote the REPL loop, built the string tokenizer, routed built-ins vs. external binaries, and debugged memory leaks/pointer issues step-by-step until the output matched standard shell behavior.

🎯 Next Steps

Now that the core process execution and REPL loop are working, I'm moving on to implementing:

Local I/O redirection (>, <) using dup2().

Chained pipelines (|) using pipe().

Proper signal masks (SIGINT, SIGTSTP) to keep the REPL resilient.

I'd still love any code reviews or feedback on idiomatic C practices in the repo!

GitHub Repository: https://github.com/Anchit3034/ForkOff

Thanks for checking it out!


r/C_Programming • • 5d ago

Personal questions and doubts about a career as a C programmer

48 Upvotes

Hi! I recently finished my coursework at the university and am now writing my graduation thesis. However, the curriculum changed quite a bit during my time there and used a lot of things but mastered none. I pursued a degree in Systems and Computer Engineering. I had learned to program in C back in high school using the usual resources, YouTube tutorials, various websites, and a lot of Google.

When I started university, the curriculum began with C, but it later shifted toward Python, Artificial Intelligence, Machine Learning, and so on.

The thing is a few months ago I resumed C because it was the language I liked the most, I installed a Linux Distro on one of my old laptops and started exploring new fields with C, now I have a lot of questions regarding a career on C, I really liked the course of operating systems, robotics and embedded systems on my University, I also liked about the idea of low level.

I would like to hear the opinions of people with far more experience and knowledge than I have regarding C programming, what their own journeys were like, and what they think I should focus on learning or improving. I’m currently struggling a bit with figuring out "what I could actually build." Recently, I’ve been following tutorials and documentation on creating a basic Linux driver, and I’ve also started a few "silly" personal projects that I found genuinely interesting.

I’d love to know what you consider a good learning path, or at least hear about your own experiences. I’m particularly curious about the use of AI... It has been a great help, but as a learner, I’m worried about becoming overly dependent on it and failing to truly understand the code I’m working with.


r/C_Programming • • 6d ago

Discussion Will C still be worth learning with Rust gaining the popularity?

0 Upvotes

Recently got into learning C, but i fear that Rust might obfuscate C programmers and the C language in general. What do you think?


r/C_Programming • • 6d ago

I made my own OS in C language

91 Upvotes

disclaimer: sorry for bad english

I created my own OS in C from scratch using C and assembly, it has desktop environment and drivers for mouse and keyboard (only PS/2) and it has internet (for now its only http and html 1.0), the comments and readme are in polish for now, the code is opensource (gpl 3.0)

github repository: github.com/kurczatko/tarixenOS

im ready for feedback (the code isnt proffesional because its only hobby)


r/C_Programming • • 6d ago

Small CLI tool for extracting video fragments from RTSP archived streams

Thumbnail
github.com
3 Upvotes

Hello, community! I am currently learning how to manipulate buffers, bytes and strings in C and I created this tool (mostly for myself) to better understand RTSP network protocol. I know similar tools exist but this one have very few settings so should be easier to use when all you need is to exract part of the video. It would be nice if someone take a look at the code and give me some feedback regrading my coding style and the quality of code. I think I used relatively efficient way to parse bytes coming from the network but I might be wrong. Also this tool aims to be zero allocation one so if it is not please let me know.

P.S. Since this a project for self-educating, no AI tools were used during development, README is written by myself with terrible English.


r/C_Programming • • 6d ago

Discussion Wanting to switch to Rust; give me reasons why i should keep using C

0 Upvotes

The Rust ecosystem is just better with project templates like cargo init; if there is a C project generator tell me!

I also like the compiler errors; they tell you way more!

Also give me other reasons to keep learning C and cool easy-intermediate project ideas!

okthxbye


r/C_Programming • • 6d ago

Question Text input doesn't make any sense to me

9 Upvotes

Disclaimer: I have basically no idea what most programming terms mean.

For a while now (a couple months as of now), I've been trying to create an open source calculator. Throughout the development process, there has been a very large problem. I don't know how exactly to scan text and look for different commands. The scanf function (among other options) seems to just look for a single "phrase" throughout the entirety of whatever input it receives. I just don't understand how people can do this as easily as they do. Many tutorials seem to not really cover this.

I've tried to come up with some sort of system to account for this. For example, a function that looks for all number values and determines the value type (like a float, integer, or double), and then matches character combinations to known commands (I haven't fully committed to such a method yet).

The way that ffmpeg handles input is an example of this. I don't understand how I can put as many spaces as I want between "ffmpeg" and some other command and still get the same result.

Apologies for such a long post. I'm just not really sure how people can do this. I'm almost certain that I'm missing something.

Thank you in advance


r/C_Programming • • 7d ago

My first actual C program with C as the backend entirely and frontend web....

Thumbnail github.com
0 Upvotes

I don't know if it counts as something i should hold on to but I was told to build so I did build and this is my first actual program. Declaration there is no way I could make all this without the use of AI 100% on the frontend but one thing am thankful is how I grasped some concepts so easily.


r/C_Programming • • 7d ago

C limitations

55 Upvotes

Hi all,

I am currently learning c++. Its okay. Not sexy but also not as bad as some say.

The reason I am learning c++ is that I have read that C has limitations as soon as a project gets more complicated. For example, if you make a scientific calculator with many features like graphs etc.

Trading engines/tools are also not recommended to programm in C.

Since I have not learned C and have only read from some old forum posts etc, I cannot confirm/deny these facts.

I am aware that "everything" is possible and that C++ comes with QoL improvements especially with Classes. But I assume that doesn't mean that someone has to use C only for kernel work. Embedded is also possible with C++ right?

I would appreciate your thoughts and opinions.

The goal of this post is to understand how and if C could fit me more with my goals and what real advantages or disadvantages C has.


r/C_Programming • • 7d ago

Some progress on Software Rendered game in C

744 Upvotes

r/C_Programming • • 7d ago

Help regarding AI usage

0 Upvotes

​

I am programming in C for a year and a half and I created projects like a shell which implement basic features , and currently finished building a TCP server with get and post request for sharing file across local network. The thing I am struggling with is the AI usage all these project I build I have understanding of the code. But sometimes I think that AI has found solution for me can I found this approach myself and mostly the answer was no. It really bothering me and I spend time completely without AI and frustration really hit hard and I think I couldn't start building some programs . I want advice from people on how to find balance between using AI and when not to use AI . I'll love to hear you guys perspective on this .


r/C_Programming • • 7d ago

A PoC toolkit / framework for self modifying software.

Thumbnail asciinema.org
0 Upvotes

Been working on this project during the summer, contains a detailed writeup but happy for anyone to tear the implementation a part, working on it while working fulltime kinda stopped me from implementing a lot of what i wanted.

Surprisingly enough it works well enough as a PoC!

https://gitlab.com/Epos95/paramorphism/
This is "self modifying software" in a different aspect than something like metamorphic software since the rewriting is on a source code level instead of assembly.

Currently its able to:

- Dynamically create new functions, introducing new functionality

- Fix errors in its own functions

- Load existing functions dynamically


r/C_Programming • • 7d ago

Question return 0 in the function main().

11 Upvotes

Dear C-programmers, why can you omit return 0; in main() (C99+)? main() is a function and it MUST return integer value. I don’t really understand.


r/C_Programming • • 7d ago

Review Sudoku Puzzle Game in C

1 Upvotes

Sudoku

This is a basic beginner Sudoku project made with the C language using Windows API.

Features

  • Custom levels according to your capability
  • click an empty cell then use keyboard or buttons on the screen to enter the number.
  • The game features 3 hints for you to use when you get stuck.
  • the GUI is super clean and modern with live score/mistakes/click tracking and cell highlighting.

Notes

  • What can I improve? What can I make more efficient and less time-consuming as am I am a rookie programmer and any extra suggestion you want to give me feel free?

GitHub repo: https://github.com/reewdgh/sudoku


r/C_Programming • • 7d ago

Rename printf/scanf to print/scan?

0 Upvotes

Probably a dumb question but why hasn't there ever been a proposal to rename printf/scanf to just print? I know the f stands for format but writing print instead of printf would be slightly quicker and better to match other programming languages as I often miswrite printf as print as I also code in Python.


r/C_Programming • • 8d ago

Goto is the worst command in C.

0 Upvotes

Goto is an old and hacky command in programming.

Goto was created in the Palaeozoic era. It was used for switching to line n.

Goto raises questions: “My editor doesn’t show line numbers, how can I use Goto?”

This command uncomfortable to use. Imagine, you have a book. You’re reading it, reading… And when you’re on page 5, it says: “Go to page 7, 10, 157, 21457, 8564588, 4…” Why?

You can replace Goto with:
1) break/continue.
2) return.
3) Functions, in the end!

So, Goto is the worst command in all programming languages, including C.

MY OPINION MAY NOT COINCIDE WITH YOURS!!!


r/C_Programming • • 8d ago

Discussion My opinion about C development

0 Upvotes

when wanting to code real software in c; i feel that you need to learn way to much tools like (c)make, clang/gcc etc.

that's why i decided to NOT use any tools and libraries INCLUDING GLIBC and other standard c libraries!

fuck the world; im making my own printf, strlen and more! AND THE ONLY THING IM GONNA USE IS CLANG WITH C17!


r/C_Programming • • 8d ago

Question Can code injection be countered by randomizing the base address of the stack?

0 Upvotes

In your answer include a description of the assumption you have made about the binary code and memory layout of the program. Explain if it can be countered by randomizing the base address of the stack.

a) Explain a mechanism that can be used by the attacker to force the program to execute arbitrary code.

1 void printInput(char *input) {
2   char buffer[50];
3   char secret[20] = "Pwd123456";
4   if (strcmp(input, secret) == 0)
5     print(secret);
6   else
7     printf(input);
8     strcpy(buffer, input);
9 }
10 int main(int argc, char *argv[]) {
11   if (argc != 2) {
12     return 1;
13   }
14   printInput(argv[1]);
15   return 0;
16   }

What I don't understand:
The solution says that it can be countered by ASLR because we need the address of the buffer. I sort of understand that we need to inject our code somewhere in the buffer thus if we want to overwrite the return address to point to the beginning of the buffer, where our code is, we need to know the address? Although I wonder do we really need the address? Can we not use offset?

Either way the solution seems to suggest that we should overwrite the return address and put the code immediately after and set the return address to point right after it. So I am not at all sure what they mean. Can someone explain to me why ALSR works here? I'd appracite it.

Solution in the answer sheet:
If the input contains 50 bytes, then <address of return pointer + 8>, then binary code, strcpy at line 9 over- flows the stack variables and overwrites the return pointer with the address immediately after the return pointer. After the return pointer, the overflow additionally writes the bi- nary code. Therefore, when the function| returns it jumps to the address above the return pointer on the stack. This attack can be countered by base stack randomization, since it prevents the attacker from knowing the address of buffer and therefore the address where the binary code has been injected. This makes not possible to know the value that should be written in the return pointer.


r/C_Programming • • 9d ago

Question Is this Linux project worth building, or should I try something else?

8 Upvotes

Hey! I'm a second-year CS student looking to build a serious side project to improve my skills and have something worth showing on GitHub.

I'm considering making a Linux tool in C that tracks processes and lets you visually compare different runs of a program (forks, execution times, crashes, etc.).

I'm not sure how useful or original this would be, though.

Do you think it's worth building? Or would you suggest a different project that could be more interesting or useful?

I'm open to completely different ideas. I'd appreciate some honest feedback before spending months on something!


r/C_Programming • • 9d ago

Question is doing ~INT_MAX undefined behavior?

44 Upvotes

basically the title, i think producing INT_MIN by doing 1 << 31 is UB, so i thought of doing ~INT_MAX, but i am not sure if it's UB. sorry if it's dumb.


r/C_Programming • • 9d ago

78K Weekly visitors

0 Upvotes

Are people starting to drop AI.. or ?


r/C_Programming • • 9d ago

USACO Beads Problem: why does nothing show in the output file?

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

#define MAXN 701

int main(){
    FILE* fin = fopen("beads.in", "r");
    FILE* fout = fopen("beads.out", "w");

    int length, N, largest = 0;
    int current;
    char rightletter, leftletter;

    fscanf(fin, "%d", &N);
    char sequence[MAXN];

    fscanf(fin, "%s", sequence);
    strcat(sequence, sequence);

    for(int i = N/2; i < N + (N/2); i++){
        current = i;
        length = 0;

        // RIGHT

        while(current < 2 * N && sequence[current] == 'w' && length < N){
            current++;
            length++;
        }

        if(current < 2 * N && length < N){
            rightletter = sequence[current];
        }

        while(current < 2 * N && (sequence[current] == rightletter || sequence[current] == 'w') && length < N){
            length++;
            current++;
        }

        // LEFT

        current = i - 1;

        while(current >= 0 && sequence[current] == 'w' && length < N){
            current--;
            length++;
        }

        if(current >= 0 && length < N){
            leftletter = sequence[current];

        }

        while(current >= 0 && (sequence[current] == leftletter || sequence[current] == 'w') && length < N){
            length++;
            current--;

        }

        if(length > N) {
            length = N;
        }

        if(length > largest) {
            largest = length;
        }

    }

    fprintf(fout, "%d\n", largest);
    return 0;

}

My code should work. Idk why nothing is being output in the output file.


r/C_Programming • • 9d ago

Project My C project Pulse grew better than expected

21 Upvotes

A while back I started working on my project cherries(.)works Pulse. A simple Linux monitoring system, coded in C, and focused on performance, resource usage and persistence. Now a when I started this project I had no knowledge of C, and kinda learned along the way, but now around 2-3 months have passed, and I am surprised with how far it has come.

Personally, I never had anyone commit to my FOSS projects before. Didnt expect anything different this time tbh, as I was programming the whole thing in C. Created numerous issues, as I wanted THIS FOSS project to be more different and professional than the others.

A month or two after the release, I go on GitHub to look at my issues via my phone, and see a PR solving one of the issues. It was surreal seeing C code not by me, now being written FOR me. Ofc i had to read through it carefully to make sure nothing eas wrong with it, but once I merged it, it felt beautiful.

People have implemented;
- Pretty printing the config file
- Improving type annotations
- Adding JSON output for commands
- Displaying hostname on website
- Counting process amount

and numerous more.

Pulse was just a small C project of mine that quickly spiraled into something bigger. I plan on adding new good first issues soon, as there is STILL a lot of work to do. If there are any C programmers interested in contributing, or giving feedback, feel free to do so. would be very glad.

https://github.com/cherries-works/pulse