Hello World and Program Anatomy

Chapter 5: Hello World and Program Anatomy

To understand C, you must look past the syntax and see how the source code maps to the machine's memory and execution model. We will analyze the classic "Hello, World!" program line-by-line.

I. The Source Code

Create a file named hello.c:

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}

II. Line-by-Line Anatomy

1. #include <stdio.h> (Preprocessor Directive)

This is not a "library import" in the Java or Python sense. It is a instruction to the preprocessor to find the file stdio.h (Standard Input Output) and copy its contents into your file before compilation. This file contains the declaration of the printf function.

2. int main() (Entry Point)

Every C program must have a function named main. It is the first code executed by the operating system when the program starts.

  • int: The return type. The program returns an integer to the OS to indicate its exit status.
  • (): The parameter list (empty in this case).

3. { ... } (Blocks)

Curly braces define the scope of the function. In C, indentation is for humans, but braces are for the compiler.

4. printf("Hello, World!\n"); (Function Call)

  • printf: A function from the standard library that prints formatted text.
  • "\n": The newline character. Without it, the next text printed would appear on the same line.
  • ;: The semicolon is a statement terminator. Every command in C must end with a semicolon.

5. return 0; (Exit Status)

Returning 0 tells the operating system that the program executed successfully. A non-zero value usually indicates an error.

III. The Binary Memory Map

When your program runs, the OS loads the binary into RAM. The memory is organized into distinct segments:

Stack (Local Variables)Dynamic GrowthHeap (malloc)Data (Global/Static)Text (Compiled Instructions)

  • Text Segment: Contains the compiled machine code instructions (read-only).
  • Data Segment: Stores global and static variables.
  • Heap: Used for dynamic memory allocation (grows upward).
  • Stack: Stores function parameters and local variables (grows downward).

IV. Compiling and Running

In your terminal:

# Compile
gcc -Wall hello.c -o hello

# Run
./hello

If you see Hello, World! on your screen, you have successfully crossed the threshold into C programming.