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
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.
C shares familiar concepts with Pascal:
surface notation is not the main difference between languages
author presents C as an important but imperfect systems-programming tool
C developed alongside Unix
rewriting Unix in a higher-level language aimed to simplify porting
B was too limited for that task
Ritchie is credited with creating C
three design pressures explain many C features:
kernels and embedded firmware illustrate C's low-level role
C can also support portable software with few runtime dependencies
learn C without treating every language feature as an ideal design
author criticizes later C standards and corporate influence on standardization
interoperability needs shared specifications
specification can describe an existing implementation
author contrasts that model with officially endorsed standards
committees are one mechanism for producing standards
author argues that committee incentives can favor accepting proposals over careful review
author also criticizes organizational representation and commercial influence
early Internet RFCs are the author's preferred example of practical specifications
author uses Pascal to illustrate divergence between a standard and implementations
author rejects much of standardized C++
author likewise excludes selected newer C facilities
examples use compiler options and a restricted C subset
C is case-sensitive
block comments use /* ... */ and do not nest
// comments end at the newline
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.
exit status communicates the program's outcome
minimal true / false programs return 0 / 1 from main
return finishes one function invocation
exit(status), declared in <stdlib.h>, terminates from any function
buffering and process operations interact
#include <stdio.h>
int main()
{
printf("Hello, world!\n");
return 0;
}
gcc -Wall -g hello.c -o hello
./hello
first example:
empty parameter lists require attention to the language version
C has no separate Pascal-style main-program statement block
main is normally called by startup code
standard library supplies commonly available facilities alongside the implementation
braces group statements into a compound statement
printf is a library-function call
printf is provided by a library, not by a dedicated language statement
printf performs formatted output
printf also returns a value
expression statements commonly perform work through side effects
string literal uses double quotes
Pascal can also put the newline into the string itself
semicolon is part of statement syntax in C
return expression; ends the current function
main's result becomes the program's termination status
#include makes header declarations available to this translation unit
dynamic linking can keep library code outside the executable file
including a header and linking a library are different operations
save the C source as hello.c
other C implementations exist, including Clang
book's normal development options:
-o selects the output name
successful build normally prints no diagnostics
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
.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
#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
example solves a quadratic equation over the real numbers
new features needed:
headers and discriminant function:
main needs local doubles for the three coefficients and discriminant
any compound statement can introduce local variables
printf accepts a format string followed by values to format
conversion directives describe the argument and representation:
%f prints a floating-point value in fixed-point notation
scanf uses a format string to describe input conversions
variable occupies memory that can also be accessed through its address
Pascal implementations also commonly pass addresses for var parameters
address-of operator: &variable
scanf's result must be checked before using the coefficients
n = scanf("%lf %lf %lf", &p, &q, &r);
invalid input prevents solving the problem
p == 0 means the equation is not quadratic
compute d = discrim(p, q, r)
print (-q-d)/(2*p) and (-q+d)/(2*p), each with %.5f
linker diagnostic can identify the driver's temporary object file
ld is the linker invoked by the compiler driver
on the Unix setup in this example, sqrt comes from libm
place libraries after the source/object files that need them
simple checks:
#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;
}
#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;
}
#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;
}
man malloc
man printf
man 3 printf # Library functions manual
man 2 close # System calls manual
missing declarations produce diagnostics such as implicit declaration
look up the function with man, e.g. man malloc
function names can collide with shell-command names
move from introductory examples to a systematic survey of C's core features
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);
}
translation units are compiled separately
file scope contains declarations and definitions
declaration supplies information about an entity
function definition = declarator/header plus body
case_up's definition supplies enough information to generate its code
char case_up(char c); declares the function without defining it
void return type expresses a procedure-like function
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]) */
/*
...
*/
}
variables defined within a function/block are local
initializer gives an object its initial value
default initialization depends on storage duration
usual implementation model:
static initial values can be encoded in the executable's data image
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 |
book's core C subset emphasizes integer and floating-point types
C exposes much of the machine's numerical representation
character constant denotes a code
integer type families:
sizeof(char) is exactly one C byte
ASCII's 0..127 range fits both signed and unsigned eight-bit char
short, int, long, and long long are signed unless unsigned is written
short / unsigned short are commonly 16-bit
short int and short are equivalent type spellings
int has historically followed practical machine/compiler conventions
many 64-bit systems still use 32-bit int
long and unsigned long have the same width
long long / unsigned long long commonly provide 64-bit integers
long is not universally large enough to store a pointer
portable size ordering:
floating types: float, double, long double
sqrt and many unsuffixed math functions operate on double
sizeof reports object/type size in C bytes
sizeof is an operator, not a function
| 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 |
literal = a value written directly in source code
integer spellings in the subset discussed:
integer-literal type depends on base, suffix, value, and language version
unsuffixed decimal integer chooses a type that can represent its value
unsuffixed octal/hexadecimal candidates include signed and unsigned types
suffixes constrain integer type selection
ordinary C character constants such as 'a' have type int
floating literals can use decimal point and exponent e/E
author considers detailed numeric-literal variants less central to this course
character constants use single quotes
common escape sequences:
string literals use double quotes and the same escapes
'M' and "M" are different:
numeric character escapes:
'\0' explicitly denotes the zero character
adjacent string literals concatenate during translation
#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;
}
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 |
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?
expressions have a broad role in C
basic arithmetic: +, -, *, /, %
mixed types and negative operands require knowing the conversion/arithmetic rules
author recommends making intended types explicit and keeping arithmetic easy to read
comparisons: <, >, <=, >=, ==, !=
extra parentheses can mark an intentional assignment in a condition
comparison result has integer value 0 or 1
logical operators: &&, ||, !
bitwise & and | work independently on corresponding bits
Pascal can select logical/bitwise behavior from operand types
~ complements bits; ^ is bitwise exclusive OR
shift operators: value << count and value >> count
x86 distinction behind the examples:
assignment expression has the newly assigned value
assignment associates right-to-left
historical explanation: assignment leaves a useful value in a machine register
compound assignment updates an object using its previous value
compound assignment evaluates its left-side object expression once
other compound assignments:
++ and -- modify their operand by one
postfix forms i++ and i-- also modify the object
prefix result = new value; postfix result = previous value
x = 7; y = ++x; -> x = 8, y = 8
book relates these operators to machine addressing modes that update registers
function call and array subscript are expression operations
f(a, b, c) includes both the callable expression and its arguments
conditional operator: condition ? when_true : when_false
conditional expressions can occur inside function arguments
comma operator evaluates left expression, then right expression
cast syntax: (type)expression
casts also appear with pointer expressions
address/member operators introduced later:
use parentheses when precedence is not obvious
| 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 |
C's statement vocabulary is small
semicolon belongs to particular statement syntax
parentheses delimit control expressions
expression statement: expression;
x + 5; or 5; is syntactically possible but normally useless
function call used as an expression statement:
empty statement is a lone semicolon
compound statement groups several statements within { }
book's style places local declarations at the start of the block
swap example declares temporary t inside the if body
if (condition) statement1; else statement2;
if adds no semicolon of its own
while (condition) body
do body while (condition);
do-while body is one statement, commonly a braced block
C for is more general than a Pascal counted loop
for(i = 1; i <= 25; i++) prints squares from 1 through 25
example puts input and summation entirely in the for header
comma expressions allow several initialization/update actions
break; exits the innermost enclosing loop or switch
continue; skips the remaining loop body
return ends the current function invocation
return expression; supplies a result
a value-returning function must supply the result its caller needs
book relates return to ABI result locations
Pascal implementations can preserve a function-result variable until return
goto transfers control to a label within the same function
label syntax in the book's C subset: name: statement
switch(expression) selects a case label according to an integer value
case labels do not end earlier cases
use explicit transfer to keep cases independent
keep switches manageable:
enum colors { red, orange, yellow, green, blue, violet };
enum colors one_color; /* can be any integer */
enum introduces an enumeration
enum colors { red, orange, yellow, green, blue, violet };
C also uses struct tag and union tag as two-part type names
traditional enum constants are integer constants
using enum types can improve intent and compiler diagnostics
enumeration constants can have explicit values
several enumeration constants may have the same value
explicit and implicit enum values can be mixed
enum declaration ends with a semicolon after }
type definition can also declare objects:
missing declaration semicolon can produce confusing later diagnostics
enum { max_buffer_size = 1024 };
replace unexplained numeric literals with meaningful names
macros historically supplied named constants
enum can introduce scoped integer constant expressions
enum naming is limited to integer constants
author reserves uppercase constant-like names for macros
#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;
}
enumeration constants are suitable case labels
example enum greek { alpha, beta, gamma = beta, delta }
adding a default can hide a forgotten new enumeration value
avoid unexplained numbered cases for named application states
names make review easier than anonymous numbers such as 12 and 13
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 */
/* ... */
}
scope determines where a variable's name is visible
storage duration determines how long its object exists
local static combines block scope with static storage duration
local static preserves changes between calls
local static hides persistent shared state behind a local name
static at file scope has a different role
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" */
pointers are central to C
machine model: memory is a linear sequence of addressable cells
compiler may keep values in registers or eliminate storage when unobservable
addresses are values that can be stored and processed
pointer variable stores an address
int *p; declares a pointer to int
&x obtains x's address; *p designates the object addressed by p
pointer assignment versus pointed-value assignment:
understand the difference before continuing
one explanation of declarators follows how a name is used
another reading treats * in a declaration as "pointer to"
void* is a generic object-pointer type
null pointer represents no object/function
pointer expressions can be conditions
#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;
}
#include <stdio.h>
int main() {
int x = 25;
int *p = &x;
printf("%d\n", p[0]);
return 0;
}
#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;
}
/* 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;
}
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
/* 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);
}
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
#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;
}
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
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;
}
C arguments are passed by value
swap(int *a, int *b):
CFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
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 */
int m[20] defines an array of 20 ints, indexed 0..19
pointer arithmetic advances in elements, not arbitrary bytes
subscript definition: a[b] == *(a+b)
sizeof on an actual array reports its whole size
whole-array assignment is not supported
subtract pointers into the same array to obtain element distance
#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;
}
#include <stdio.h>
int main() {
int x;
int *p;
int m[20];
x = 25;
p = &x;
m = p;
return 0;
}
#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;
}
#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;
}
int main(void) {
int arr[5];
/* Intentional mismatch to trigger a warning */
int *ptr = &arr;
return 0;
}
#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;
}
#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;
}
#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);
malloc and free are library facilities
calloc and realloc provide additional allocation operations
include <stdlib.h> for allocation declarations
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
#include <stdio.h>
#include <unistd.h>
int main()
{
int i;
for (i = 0; i < 1000; i++) {
printf("hello there\n");
sleep(1);
}
return 0;
}
#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;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p;
p = malloc(sizeof(*p));
return 0;
};
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p;
p = malloc(sizeof(*p));
*p = 10;
p = NULL;
free(p);
return 0;
};
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p;
p = malloc(sizeof(*p));
*p = 10;
p = NULL;
free(p);
return 0;
};
#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;
};
#include <stdlib.h>
int main()
{
int *p;
p = malloc(sizeof(*p));
free(p);
*p = 5;
return 0;
}
#include <stdlib.h>
int main()
{
int *p;
p = malloc(sizeof(*p));
free(p);
free(p);
return 0;
}
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);
const qualifies a type to restrict modification through it
const int iteration_count = 78;
variable-length arrays use runtime size expressions in supported C modes
const int *p points to const-qualified int
int * const q = &x makes the pointer object constant
const-qualified pointer parameters document read-only access
casts can remove a pointer's const qualification
#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;
}
#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;
}
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.
x and literal 22 can yield the same value without being equivalent expressions
object-designating expressions can provide a location as well as a value
array elements and record members also behave like variables
example: int *ptrvec[20]; ptrvec[5] = &x;
assignment/address-taking need the object's location, not merely its old value
x + 1 produces a value but does not designate an assignable object
lvalue is the traditional term for an object-designating expression
not every lvalue is modifiable
C++ has additional value categories such as xvalue
#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;
}
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.
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 };
/* ... */
}
array initializer lists elements inside braces
omitted array bound can be inferred from its initializer
automatic local arrays can be initialized on entry
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;
}
text length is often unknown when the program is written
classic Pascal short strings store length in a leading byte
C string is a sequence of chars ending at the first zero byte
null termination permits arbitrary length subject to storage limits
length function receives a pointer to the first char
read-only parameters accept data already exposed through const-qualified interfaces
string literals must not be modified
C string literals have char array type for historical compatibility
use pointer-to-const parameters when the pointed-to objects will not be changed
first string_length implementation scans by index
equivalent loop forms:
strlen from <string.h> provides standard byte-length calculation
string_copy(char *dest, const char *src):
pointer version advances dest and src while copying
compact idiom: while((*dest++ = *src++)) {}
strcpy from <string.h> performs this kind of copying
these copy routines assume source and destination do not overlap
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
"Hello" supplies six char elements: five letters and a terminating zero
read-only literal storage can be shared between executing program instances
in most expression contexts, a string literal converts to a pointer to its first char
C and C++ differ in literal element qualification
literal indexing follows normal array/pointer rules
char str[] = "Hello" initializes a separate six-element array
array and pointer have different operations and sizes
/*
* - 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;
}
main can receive int argc, char **argv
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.
#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:
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;
}
}
}
two worked programs connect the C facilities to earlier Pascal/assembly examples
recursive Tower of Hanoi:
fprintf(stderr, ...) sends diagnostics to the error stream
wildcard match(str, pat) uses pointer advancement
alternative splits star handling into starmatch
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
high-level standard I/O is provided through <stdio.h>
| 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;
}
standard input/output need not be keyboard and screen
getchar() reads one byte from stdin
successful byte is returned as unsigned char converted to int
EOF is a negative integer macro, commonly -1
example reads until EOF and prints OK for each newline
line-length counter:
check the int result before converting it to char
putchar(c) writes one byte to stdout
putchar returns the written character on success or EOF on error
untilspace example prints each line's prefix before the first space
#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;
}
#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != EOF)
putchar(c);
return 0;
}
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 |
printf(const char *format, ...) is variadic
printf interprets ordinary characters and % conversion directives
conversion layout: % flags width .precision length specifier
width does not truncate a number
precision depends on conversion
integer precision gives a minimum number of digits
length modifiers select the expected numeric type
% #7.4Lg combines:
printf can obtain width/precision from int arguments
scanf is also variadic, but its formatting rules differ from printf
scanf conversion directive contains %, optional *, width, length, specifier
whitespace in a scanf format skips input whitespace
ordinary format characters must match input literally
scanf pointers must match the destination type exactly
scanf distinctions:
numeric scanf lengths:
string input requires an explicit bound
scanf cannot receive width through a separate * argument
author limits scanf to simple programs
scanf returns successful assignments, not bytes consumed
#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;
}
void test_int(char c) {
}
int main() {
char c = 'a';
test_int(c);
return 0;
}
.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
#include <stdio.h>
int main() {
char c;
scanf("%c", &c);
printf("%c", c);
return 0;
}
#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;
}
| 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)++;
}
}
opening a file creates another I/O stream
FILE* identifies library-managed stream state
copying a FILE* copies a reference to stream state, not the state itself
stdio has separate function names for operations on an explicitly supplied stream
fopen(name, mode) returns a FILE*
fopen modes:
b selects binary mode where text/binary streams differ
NULL means opening failed
real input/output failures are part of normal program design
error policy depends on the caller's context
errno records errors for interfaces that document using it
function documentation lists possible errors
perror(context) prints a contextual errno diagnostic to stderr
author prefers English diagnostics while developing programs
fprintf(stderr, ...) prints a custom diagnostic
fclose(stream) closes the stream and releases its library resources
check fclose after writing
kernel buffering can similarly delay errors until a low-level close/writeback operation
fgetc(stream) / fputc(character, stream) generalize getchar / putchar
ungetc(character, stream) pushes a character back for a later read
lexical scanner may read one character beyond a token
an explicit lookahead buffer is an alternative to ungetc
fprintf / fscanf add a FILE* before the format string
intfilesum reads integers from an already opened stream
stdin, stdout, stderr identify the standard streams
ungetc(c, stdin) supplies standard-input pushback
#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 <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;
}
| 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.
#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.
text streams commonly contain newline-separated lines
fputs(s, stream) outputs a string without interpreting a format
fgets(buffer, size, stream) needs the destination capacity
with a usable positive capacity, fgets reads at most size-1 bytes
string50 example reads into char buf[51]
rejected line handling:
accepted line handling:
puts(s) outputs to stdout and adds a newline
do not use gets for input
gets cannot know the destination's bounds
writing beyond a local array can corrupt nearby stack state
crafted overlong input can redirect program control flow
memory corruption can make a program act outside its intended function
buffer overflow exploit is the name for exploiting an out-of-bounds write
terminology aside: hacker also has a longstanding noncriminal programming meaning
use bounded input interfaces instead of gets
passing an uninitialized pointer does not create input storage
storage always has a size, whether static or dynamically allocated
arbitrary-length input needs managed growth
#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;
}
.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
#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;
}
/*
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;
}
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)
.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
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 */
stdio input can fetch a block from the OS and return one requested byte
stdio output accumulates data before larger writes to the OS
input buffering is often transparent to a simple stream-processing program
output buffering can hide diagnostic messages before a crash
fflush(output_stream) explicitly sends pending library output onward
fflush(stdin) is not a portable way to discard interactive input
output is also flushed when required by a full buffer and by normal termination
terminal output is commonly line-buffered rather than fully buffered
line buffering flushes on newline
precise automatic flushing conditions depend on the stream setup
stderr is normally unbuffered and initially not fully buffered
setbuf / setvbuf configure buffering before ordinary stream operations
BUFSIZ and actual system-call transfer sizes are implementation details
| 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 */
sprintf(buffer, format, ...) writes formatted text into memory
snprintf also receives destination capacity
availability of declarations depends on language mode and library interfaces
format a number or record before sending it through a lower-level interface
sprintf's successful return is output length excluding the final zero
sscanf(source_string, format, ...) parses existing text
author prefers more explicit parsing when scanf-style diagnostics are inadequate
In practice, C programmers usually use system calls
(open, read, write,
close) when working with binary data.
C programs can process both textual and binary files
fgetc/fputc also handle arbitrary bytes
book often prefers low-level OS I/O for binary random-access workloads
stdio's main conveniences are formatting and buffering
fread/fwrite provide block operations within the FILE* interface
fread(ptr, size, count, stream) / fwrite(ptr, size, count, stream)
result counts complete elements transferred, not bytes
feof(stream) reports an encountered EOF condition
fseek(stream, offset, whence) changes a seekable stream's position
using size = 1 makes the transferred-element count a byte count
linked lists and trees need compound objects as well as pointers
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.
structure combines named fields that can have different types
structure declaration:
student example combines:
structure tags use a separate C namespace from ordinary identifiers
structure size can exceed the sum of its field sizes
compiler inserts padding between fields where needed
alignment affects both total size and member offsets
use sizeof to allocate storage for the actual compiled structure
members retain declaration order, but padding and ABI details vary
serialize explicitly when exchanging data across implementations
structures can be assigned, passed, and returned by value
book discusses using memcpy to make structural copying conspicuous
field access through a pointer can be written (*p).year
p->year is the concise equivalent of (*p).year
bit-fields assign a width to an integer member
bit-field layout is implementation-dependent
implementations may support additional bit-field base types
understand bit-fields when reading code
struct vec {
int x;
int y;
};
int main() {
struct vec v1;
v1.x = 1;
v1.y = ;
return 0;
}
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
#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;
}
.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
#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;
}
#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;
}
struct list {
int data;
struct list *next;
};
Write the function to convert an array to a list:
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;
}
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);
}
}
C examples assume the earlier Pascal list algorithms are understood
node contains payload and pointer to next node
build a list from an integer array by appending:
alternative: scan array backward and prepend each element
recursive construction:
summing a list:
delete nodes without reading freed memory:
recursive deletion:
filter example removes every negative-valued node
deletion changes the pointer that leads to the current node
struct item **pcur tracks the incoming link
function delete_negatives(struct item **pcur) can use that same loop
recursive filter first processes the tail through &node->next
alternative API returns a replacement head
author dislikes this replacement-head convention despite its popularity
author prefers the pointer-to-pointer form because the function completes the update
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
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.
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 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);
}
node contains previous and next links
struct dbl_item contains double data plus prev and next pointers
conditional expressions can select which pointer field to update
remove first only after checking it exists
insertion relative to an existing current node:
unlink current by repairing both directions
if traversal position is no longer needed:
to continue traversal, save the successor/predecessor before freeing current
#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;
}
#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;
}
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.
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);
}
}
}
binary-tree node contains payload and left/right child pointers
struct node contains int val and left/right pointers
iterative traversal must store the information recursion would remember
explicit stack models recursive function frames
explicit traversal state is useful for pausing and resuming between requested values
search-tree ordering:
insertion base case: *root is NULL
equal value: example does nothing
smaller value -> recursively insert left
plain BST shape depends on insertion order
some workloads produce acceptable shapes without balancing
#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;
}
#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;
}
#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, ¤t);
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, ¤t);
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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
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
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
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;
};
union members overlap the same storage
conceptual interpretation: values can belong to one of several alternative member types
union sample_un can hold an int, a double, or char str[16]
unions can save storage for mutually exclusive alternatives
union can illustrate an integer's underlying byte representation
placing a union inside a struct allows a separate discriminator/tag
expression-token example:
anonymous union can expose its members directly within the enclosing structure
author avoids anonymous unions in this course
#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]);
}
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;
typedef introduces an alias for a type rather than a new object
structure aliases can avoid repeating struct in declarations
#include <stdio.h>
typedef int *intptr;
int main()
{
int x = 5;
intptr p;
p = &x;
printf("%d\n", *p);
return 0;
}
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.
macroprocessor / preprocessor:
preprocessor directive:
macro names:
preprocessing works with tokens before C syntax, types, and scopes are
analyzed:
#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;
#define NAME replacement:
macro replacement need not be a complete expression or statement:
book discourages disguising ordinary C syntax this way
Use UPPERCASE for macros to avoid name conflicts:
#define count 35
int f(int n, const char *str)
{
int count;
/* ... */
}
macros ignore scope:
convention: uppercase macro names, lowercase ordinary identifiers
uppercase is a programmer convention
book's historical explanation for uppercase constants:
enum constants behave as ordinary scoped identifiers:
public interfaces may require keeping an existing uppercase name:
mixed historical naming creates another consideration:
follow an existing project's conventions
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; \
/* ... */
}
function-like macro:
parentheses protect an expression macro from surrounding precedence:
parentheses do not prevent repeated evaluation:
book recommends avoiding macros when ordinary C facilities suffice
multiline macro:
macros can generate families of similar functions:
token pasting with ##:
multiline macro difficulties:
compiler option -E:
stringification with # before a macro parameter:
adjacent string literals allow a shorter replacement:
#define MAX (A, B) ((A) > (B) ? (A) : (B))
int main() {
int x;
char *y;
x = 7;
y = MAX(5, x);
return 0;
}
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)
statement-like macro should work wherever one statement is allowed:
solution: #define MYMACRO(arg) do { f(arg); g(); } while(0)
book treats this idiom as a workaround made possible by existing C syntax
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
conditional compilation selects which source fragments reach the
compiler:
same general mechanism appeared in the Pascal and NASM examples
#if 0 ... #endif temporarily excludes a source fragment:
#if ... #else ... #endif selects one of two implementations:
set the option externally:
#ifndef can provide a default without overriding a supplied option:
#ifdef / #ifndef also commonly control debugging output
#if requires an integer expression evaluable during preprocessing:
defined(NAME) tests whether a macro exists:
#elif adds another conditional branch:
macros can serve only as presence / absence flags:
#undef MYMACRO
#ifndef BUFFER_SIZE
#error Please specify the buffer size
#endif
Macro names __LINE__, __FILE__,
__DATE__, __TIME__ are always defined.
#undef MYMACRO:
#error message:
#line:
predefined macros:
#include <stdio.h> /* for external libraries including standard library */
#include "mymodule.h" /* for your modules */
two common inclusion forms:
book's intended convention:
kernel code illustrates that C can be used without the ordinary hosted library
standard headers need not correspond to physical files:
third-party library headers raise the practical inclusion question too:
usual GCC search behavior:
installed third-party headers commonly share system include locations:
practical rule used in this book:
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.
preprocessor nesting and C statement nesting are separate structures:
book's formatting convention:
example: selecting a sorting implementation:
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.
C separate compilation resembles the earlier assembly approach:
divide functions and global objects among .c files:
linking options:
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[];
NASM comparison:
C functions / file-scope objects normally have external linkage:
calling a function defined elsewhere:
incremental rebuild:
declaring an external variable:
book discourages communication through mutable global variables:
shared read-only tables avoid that particular problem:
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.
copying external declarations into every client is difficult to
maintain:
example: func changes from two int parameters to three:
changing an argument from int to double creates a similar mismatch
module header keeps exported declarations in one place:
clients use #include "m1.h":
implementation must include its own header:
mark private functions and file-scope variables static:
main is the usual exception:
#include <stdio.h>
int mult(int x, int y);
int main() {
printf("%d\n", mult(2, 4));
return 0;
}
.c file. Exported ones are declared in the header
.h, internal ones are static..h, or in the
.c file if internal.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:
newmod.c and
newmod.hnewmod.c the directive#include newmod.h
newmod.h the directives#ifndef NEWMOD_H_SENTRY
#define NEWMOD_H_SENTRY
#endif
shared user-defined types belong in a header:
shared macros also belong in headers
basic division between implementation and interface:
repeated inclusion can happen indirectly:
consequences depend on the header contents:
removing a direct include is a fragile solution:
header guard / sentry macro:
first inclusion:
later inclusion in the same translation unit:
book describes guards as a practical use of conditional compilation
a declaration-only header may not strictly need protection yet
new-module routine:
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.
struct item; declares a type without defining its members:
incomplete object type cannot provide storage / layout for an object definition
incomplete types allow recursive links:
using struct item * can introduce the tag without a preceding definition
forward declarations reduce header dependencies:
opaque type interface:
enum forward declarations are a different case:
formatting principles have appeared throughout the book
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.
English source-code conventions do not determine the user's interface language
separate translatable messages from program logic:
gettext provides message lookup:
localization can be disabled by changing the wrapper:
marking user-visible messages prepares a program for translation:
book's rule: provide localization or at least keep a consistent English baseline
following example demonstrates that arrangement with gettext
starting program prints a greeting and a farewell:
first preparation step:
N_(STR) can mark text for translation later without calling gettext
immediately:
headers needed for the localized version:
gettext configuration identifies:
example domain: hellobye
configuration constants and wrappers:
startup sequence:
create the translation template:
prepare a language catalog:
fill each msgstr with the corresponding Russian message:
compile catalogs:
catalog placement follows base / language / category / domain.mo:
build and try the program:
when source messages change:
example covers only the simplest gettext facilities
gettext is one possible localization mechanism:
# 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"
#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;
}
# 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"
#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;
}
#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;
}
#include <stdio.h>
int main()
{
printf("Hello, world!\n");
printf("We are speaking!\n");
printf("Good bye, world!\n");
return 0;
}
# 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"
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;
}
# 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"
{ on new line in function definitions_ to avoid
conflicts with system namessource code is read by people as well as processed by computers
book's source-text conventions:
indentation displays nesting:
brace styles discussed:
book's function formatting:
preferred shape for a function:
C is case-sensitive:
book's usual identifier convention:
mixed-case type names do appear in some C libraries
avoid inventing identifiers beginning with _:
C declarations can have substantial internal structure:
struct / union formatting:
enum formatting:
initializer formatting:
while(condition); is visually ambiguous:
book recommends braces for every do / while body:
indent a final return just like every other statement:
indent local declarations inside the function too
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:
+=,
<<=, ... and '++', '--' should be leftmost in
expressionsfunction_with_side_effects(<parameters>);
result = function_with_side_effects(<parameters>);
while loop of the
"fetch-test-process" type:while ((c = getchar() != EOF) {
/* ... */
}
several side effects in one expression require attention to sequencing
f(h1(), h2(), h3()) evaluates the arguments before entering f
ordinary arithmetic operands also lack a general left-to-right guarantee
b = (a += 5) + (a *= 2) modifies a without the required sequencing
reversing a guessed operand order does not repair that expression
book reports one compiler producing a = 12, b = 24
full-expression boundaries complete preceding side effects
sequencing also occurs within selected operators
author recommends limiting side effects in each expression
book's explanation of a side effect:
book distinguishes this expression-centered meaning from ordinary
actions:
C makes assignments and increments expressions:
author connects the wider terminology to the influence of C-like languages
string-copy idioms illustrate the readability problem:
array[array_filled++] = x combines two actions:
clearer separation in the book's style:
banning every side effect would rule out ordinary useful C programs
input loop example:
common loop pattern: retrieve -> test -> process
another implementation uses for(;;) or while(1):
condition-side retrieval has a reasonable purpose in this pattern
book restricts that exception to retrieval loops:
many C functions perform an action and return its status:
author considers action-plus-status an established C idiom
book's practical rules for effectful code:
examples accepted by this style:
examples discouraged by this style:
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.
output parameter sends information back to the caller:
inout parameter carries information both ways:
one inout value can instead be passed by value and returned:
return-value form is more flexible for an ordinary calculation:
a list head pointer is not the whole list:
distinguish computing a value from modifying an existing object:
book prefers a pointer-to-pointer interface for that mutation:
book criticizes realloc's return-value interface on similar grounds
several outputs raise an interface choice:
book's recommendation for action-oriented functions:
standard interfaces do not always follow that recommendation:
pointer parameters intended only for reading should point to const
data:
array and function pointers can make declarations difficult to read
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;
int m[3][4]:
one pair of square brackets for each dimension:
array-pointer relationships can take time to understand
question behind multidimensional indexing: what is the type of m?
in most expressions an array converts to a pointer to its first element
m[1] = *(m + 1):
int (*p)[4]: pointer to an array of 4 ints
int *q[4]: array of 4 pointers to int
int z[10][15][20]: array of 10 two-dimensional slices
#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;
}
#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; */
}
.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
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
compiled functions have callable addresses
functions can share a profile while performing different operations:
common profile: double result, const double* array, int size
assign a function address:
call through the pointer:
function designators usually convert to function pointers automatically
the original C notation distinguished a function from its address explicitly
standard C allows fptr(arguments)
choice of call notation is a style decision
generalizing a list operation:
pass the deletion criterion as int (*crit)(int)
delete_from_int_list receives the address of the link that points to the current node
#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;
}
#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;
}
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);
callback: one module supplies a function for another module to call
a reusable service knows the callback's required profile
processing can depend on earlier items
void* userdata carries the address of caller-owned state
generalize binary-tree traversal:
callback profile: void callback_function(int num, void *userdata)
int_bin_tree_traverse:
printing callback:
summing the tree requires state across callback invocations
minimum, maximum, and count in one traversal:
Please describe the following functions:
int (*funret(int x))(int, int)
{
/* ... */
}
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);
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]
{
/* ... */
}
select_segment is a function taking 2 int parameters and
returning a pointer to an array of 10 doubles.
double (*(*selptr)(int, int))[10];
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)
{
/* ... */
}
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);
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
declarations combine prefixes and suffixes
examples of nested declarations:
a function can accept and return the same function-pointer type
parameter names may appear in a function-pointer declaration
typedef breaks the declaration into understandable parts
reading procedure:
replace_f_ptr example:
funvec example:
C restricts how array and function types can be combined
invalid examples illustrate the distinction:
standard library supplies many commonly needed operations
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);
}
#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
calloc(nmemb, size): allocate space for nmemb elements of size bytes each
realloc(ptr, size): change an existing allocation's size
special cases:
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);
standard function names make common operations immediately recognizable
learning the functions does not replace understanding strings
string and memory function declarations are in string.h
strlen(str): length before the terminating zero byte
strcpy(destination, source): copy a complete string, including its terminating zero
strncpy(destination, source, n): write exactly n bytes when n is nonzero
strcpy and strncpy return the destination address
strdup(source): allocate and return an independent string copy
strcmp(s1, s2): compare complete strings lexicographically strncmp(s1, s2, n): compare at most n character positions
make equality tests explicit
strchr(s, c): first occurrence of a character
strrchr(s, c): last occurrence
strstr(haystack, needle): first occurrence of a substring
memset(memory, value, size): fill a byte region
memcpy(dest, src, size) and memmove(dest, src, size): copy raw bytes
#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;
}
#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);
}
#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);
}
#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;
}
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;
}
randomness is useful for games, simulation, and security
operating systems gather unpredictable information from available sources
the book demonstrates obtaining random bytes from Linux /dev/random
ordinary pseudorandom sequences can suffice for nonsecurity tasks
stdlib.h declares rand and srand
srand(seed) initializes generator state
ordinary demonstration seed: srand(time(NULL))
time-based seeding is unsuitable for passwords and secrets
mapping results to a smaller interval:
#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;
}
#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;
}
#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;
}
#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);
variadic function: accepts a variable number of arguments
traditional declaration: named parameters followed by ...
implementation depends on the calling convention
the variable argument list contains no automatic count or type description
sum example uses integer 0 as an end marker
print_times example uses alternating string pointer / int pairs
vprintf, vfprintf, vsprintf, vsnprintf and the vscanf family accept va_list
#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;
}
#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 terminal program:
ncurses handles differences between terminals
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.
the examples cover only a small part of the library
related libraries supply higher-level interface components
#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
example: center "Hello, world!", wait 5 seconds, then finish
available behavior depends on the selected terminal description
initscr(): initialize ncurses and take control of the terminal getmaxyx(stdscr, row, col): obtain screen height and width
getmaxyx is a macro, not an ordinary function
move(y, x): set the cursor's position in the window
use ncurses output functions while ncurses manages the screen
addstr(message): write a string at the current cursor position addch(character): write one character
finish the demonstration:
#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;
}
#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;
}
Write a program that shows stars for different combination of foreground and background colors.
#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;
}
character attributes control appearance
attributes can work independently of color:
check color support with has_colors()
remaining color examples assume color is available and enabled
eight basic named colors:
color pair = foreground color + background color
check supported ranges after start_color
eight foregrounds times eight backgrounds gives 64 combinations
pairs can represent interface roles instead of unique color combinations
A_BOLD may display as brighter foreground color on some terminals
color demonstration fills the screen with stars
keep the eight color constants in an array
setpair associates a pair number with its two colors
make_line draws one foreground across strips of different backgrounds
make_screen clears the display and fills it with these rows
input loop recolors the existing display
complete example joins initialization, drawing, recoloring, and cleanup
#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;
}
#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;
}
#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;
}
#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;
}
Write a program that sets direction for star movements with
h j k l keys.
#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;
}
canonical terminal input:
full-screen interfaces usually need different behavior
ncurses exposes these choices separately
cbreak(): receive characters without waiting for a complete line
raw(): also disable the driver's usual special handling of control characters
noecho(): disable automatic echo; echo() re-enables it keypad(stdscr, 1): translate recognized key escape sequences into key codes
getch(): read an input event as int
Enter and Backspace need attention to terminal behavior
input events can also report mouse activity or a terminal resize
interactive example: move "Hello, world!" with arrow keys
split drawing and movement into helpers
handle_resize recomputes the permitted message position
main loop dispatches getch results with switch
formatted output:
#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;
}
blocking input prevents an animation from advancing while no key is pressed
timeout(milliseconds) selects the waiting policy
moving-star example:
state structure stores current x/y and velocity dx/dy
#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;
}
#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;
}
#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;
}
#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.
;; 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
experiment: identify which parts of a C executable come from the language
and which come from startup code and library services
initial greeting program uses printf
a small dynamically linked executable omits most library machine code
-static requests static linking
replace formatted output with the operating system's write operation
using write alone still leaves normal C startup and library linkage
to remove libc, replace the startup routine as well
initial 32-bit process stack and C function arguments have different layouts
book's Linux i386 _start:
FreeBSD i386 variant:
next component: private syscall wrappers
three-argument syscall wrappers can share one assembly body
Linux i386 body:
error convention:
FreeBSD i386 body:
greet3 uses only the private sys_write wrapper
build separate object files:
when the host defaults to 64-bit objects:
a minimal executable can be much smaller
control over startup and runtime dependencies is useful for kernels and firmware
compiler-generated helpers can still introduce unresolved references
compiler-generated memory operations are another dependency
distinguish a language's usable subset from a particular compiler's output
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
#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;
}
#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;
}
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;
}
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;
}
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;
}
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
#include <unistd.h>
int main()
{
write(1, "Hello, world\n", 13);
return 0;
}
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
/*
* - 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;
}
#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;
}
#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;
}
#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.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
#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;
}
#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;
}
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
%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
#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