কম্পিউটার বিজ্ঞান · বই 3 · স্নাতক প্রথম বর্ষ

University Computer Science — Year 1

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।

University Computer Science — Year 1 · স্নাতক প্রথম বর্ষ

4Pointers and Arrays

To read a whole number typed at the keyboard, a C program calls scanf("%d", &n). Forget the ampersand, write scanf("%d", n), and the compiler warns while the program, with luck, crashes; without luck it writes the number somewhere in memory and carries on. The & hands scanf the place where n lives, so that it can store a value there: Chapter 3 showed that a function receives copies, and a copy of n would be of no use. This chapter is about such places, the addresses of memory, and about the values that hold them, pointers. They are the most powerful feature of C and the source of its worst bugs, and the two are the same thing.

You already know

Memory is a long row of bytes, each with a number, its address. A variable occupies a few consecutive bytes, from a first address on: an int four bytes here, a double eight. The school volumes drew it as a row of numbered boxes, and showed that a Python list holds references to its elements rather than the elements themselves.

4.1 Addresses and pointers

Definition 4.1 (Address, pointer, dereferencing)

The address of an object is the address of its first byte; the operator & gives it: &n. A pointer is a value that is an address together with the type of what is stored there; a variable declared int *p holds a pointer to an int. The operator * applied to a pointer, *p, designates the object at that address: reading *p reads it, assigning to *p writes into it. Following a pointer in this way is called dereferencing it.

#include <stdio.h>

int main(void)
{
    int n = 5;
    int *p = &n;                         // p holds the address of n
    printf("n = %d, *p = %d\n", n, *p);
    printf("p == &n: %d\n", p == &n);
    *p = 7;                              // writes 7 at that address: into n
    printf("after *p = 7: n = %d\n", n);
    printf("sizeof n = %zu, sizeof p = %zu\n", sizeof n, sizeof p);
    int *nowhere = NULL;
    printf("nowhere == NULL: %d\n", nowhere == NULL);
    return 0;
}
Listing 4.1. A variable and a pointer to it code/bachelor-1/04-pointers-and-arrays/listings/addr.c
$ gcc -std=c17 -O2 -Wall -Wextra -o addr addr.c -lm && ./addr
n = 5, *p = 5
p == &n: 1
after *p = 7: n = 7
sizeof n = 4, sizeof p = 8
nowhere == NULL: 1
Output 4.1. Writing through p changed n.

The type in int * matters twice: it tells the compiler how many bytes *p covers and how to read them, and it lets the compiler refuse double *q = &n;. A pointer itself occupies 8 bytes on this machine, whatever it points to, because every address of a 64-bit process fits in 64 bits. The * has two roles in the text: in a declaration it says “pointer to”; in an expression it dereferences.

Memory after *p = 7, with made-up addresses (the real ones change from run to run). n occupies the four bytes from address 1000; p, eight bytes from 1008, holds the number 1000. Writing *p writes into the bytes at that number, which are n’s.
Memory after *p = 7, with made-up addresses (the real ones change from run to run). n occupies the four bytes from address 1000; p, eight bytes from 1008, holds the number 1000. Writing *p writes into the bytes at that number, which are n’s.

Definition 4.2 (Null pointer)

The null pointer of a pointer type, written NULL (or 0), compares unequal to the address of every object and function. It means “points to nothing”: a function that finds nothing returns it, and a pointer variable not yet given a target should hold it. Dereferencing the null pointer is undefined behaviour.

On this system the first page of memory is never mapped, and dereferencing NULL stops the program at once, the best outcome an undefined behaviour can have (Section 4.4).

4.2 A pointer passed to change the caller’s data

Passing by value still holds: a function receives copies. But the copy of an address is the same address, and through it the function reaches the caller’s variable. The failed swap of Chapter 3 works once it receives addresses.

#include <stdio.h>

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

int main(void)
{
    int x = 1, y = 2;
    swap(&x, &y);
    printf("after swap: x = %d, y = %d\n", x, y);
    return 0;
}
Listing 4.2. A swap that swaps code/bachelor-1/04-pointers-and-arrays/listings/swap_ptr.c
$ gcc -std=c17 -O2 -Wall -Wextra -o swap_ptr swap_ptr.c -lm && ./swap_ptr
after swap: x = 2, y = 1
Output 4.2. This time x and y are exchanged.
The frames at the end of the fixed swap. Its parameters hold the addresses of main’s variables: writing *a and *b writes into main’s frame. This is the only way a called function reaches the frame of its caller.
The frames at the end of the fixed swap. Its parameters hold the addresses of main’s variables: writing *a and *b writes into main’s frame. This is the only way a called function reaches the frame of its caller.

The same device gives a function several results: it returns one, or none, and writes the others through pointer parameters supplied by the caller. scanf works this way: it returns the number of values it converted, and stores each value at the address it was given.

#include <stdio.h>

void divmod(int a, int b, int *quotient, int *remainder)
{
    *quotient = a / b;
    *remainder = a % b;
}

int main(void)
{
    int q, r;
    divmod(2026, 7, &q, &r);
    printf("2026 = 7 * %d + %d\n", q, r);
    return 0;
}
Listing 4.3. Two results through two pointers code/bachelor-1/04-pointers-and-arrays/listings/divmod.c
$ gcc -std=c17 -O2 -Wall -Wextra -o divmod divmod.c -lm && ./divmod
2026 = 7 * 289 + 3
Output 4.3. 2026=7×289+32026 = 7 \times 289 + 3.
#include <stdio.h>

int main(void)
{
    int n;
    if (scanf("%d", &n) != 1) {          // &n: the address of n
        printf("not a number\n");
        return 1;
    }
    printf("%d days = %d weeks and %d days\n", n, n / 7, n % 7);
    return 0;
}
Listing 4.4. Reading a number: scanf stores it at &n code/bachelor-1/04-pointers-and-arrays/listings/read_number.c
$ gcc -std=c17 -O2 -Wall -Wextra -o read_number read_number.c -lm && ./read_number
45 days = 6 weeks and 3 days
Output 4.4. With 45 on standard input.

A pointer parameter that the function only reads from is declared const int *p: the function receives a read-only view and the compiler refuses *p = 0. The const documents the contract and is checked: a reader of the prototype int min_max(const int *a, size_t n, int *min, int *max) knows that the array is read and that *min and *max are written.

4.3 Arrays and pointer arithmetic

Definition 4.3 (Array, array-to-pointer conversion)

An array of C, declared int a[5], is a block of a fixed number of elements of one type, stored contiguously in memory; its size is fixed when it is created. In almost every expression, the name of an array is converted into a pointer to its first element: this is the array-to-pointer conversion. The exceptions are sizeof a and &a, where a stays the whole array.

Definition 4.4 (Pointer arithmetic)

If p points to element ii of an array, p + k points to element i+ki + k: pointer arithmetic counts in elements, not bytes, so the address grows by kk times the size of an element. The result must point into the array or exactly one element past its end. The difference q - p of two pointers into the same array is the number of elements between them, of type ptrdiff_t. By definition a[i] means *(a + i).

#include <stdio.h>

int main(void)
{
    int a[5] = {10, 20, 30, 40, 50};
    for (int i = 0; i <= 5; i++)         // i = 5: the one-past-the-end pointer, never dereferenced
        printf("a + %d is %2td bytes after a\n", i, (char *)(a + i) - (char *)a);
    printf("a[3] = %d, *(a + 3) = %d\n", a[3], *(a + 3));
    int *p = &a[1], *q = &a[4];
    printf("q - p = %td elements\n", q - p);
    printf("sizeof a = %zu bytes, %zu elements\n", sizeof a, sizeof a / sizeof a[0]);
    return 0;
}
Listing 4.5. The layout of an array code/bachelor-1/04-pointers-and-arrays/listings/array_layout.c
$ gcc -std=c17 -O2 -Wall -Wextra -o array_layout array_layout.c -lm && ./array_layout
a + 0 is  0 bytes after a
a + 1 is  4 bytes after a
a + 2 is  8 bytes after a
a + 3 is 12 bytes after a
a + 4 is 16 bytes after a
a + 5 is 20 bytes after a
a[3] = 40, *(a + 3) = 40
q - p = 3 elements
sizeof a = 20 bytes, 5 elements
Output 4.5. Elements four bytes apart; a + 5 is one past the end.

The pointer a + 5 is allowed to exist, to be compared and subtracted, but not to be dereferenced: it is the end mark of every loop of the form for (p = a; p < a + n; p++). A pointer further away, or before the start, is undefined behaviour even if it is never dereferenced.

An array of five int. The pointer a + k designates element k, 4k bytes from the start; a[k] and *(a + k) are the same element. The position after the last element can be pointed to but holds nothing of the array.
An array of five int. The pointer a + k designates element kk, 4k4k bytes from the start; a[k] and *(a + k) are the same element. The position after the last element can be pointed to but holds nothing of the array.

Since an array name becomes a pointer, an array is never passed to a function: its address is. A parameter written int a[] is a pointer int *a, the function cannot know how many elements follow, and the length must travel in a separate parameter. sizeof on such a parameter gives the size of a pointer; GCC warns.

#include <stdio.h>

long sum(int a[], size_t n)              // the same as: long sum(int *a, size_t n)
{
    printf("in sum:  sizeof a = %zu\n", sizeof a);
    long s = 0;
    for (size_t i = 0; i < n; i++)
        s += a[i];
    return s;
}

int main(void)
{
    int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    printf("in main: sizeof days = %zu\n", sizeof days);
    printf("sum = %ld\n", sum(days, sizeof days / sizeof days[0]));
    return 0;
}
Listing 4.6. An array parameter is a pointer code/bachelor-1/04-pointers-and-arrays/listings/decay.c
$ gcc -std=c17 -O2 -Wall -Wextra -o decay decay.c -lm && ./decay
decay.c: In function 'sum':
decay.c:6:48: warning: 'sizeof' on array function parameter 'a' will return size of 'int *' [-Wsizeof-array-argument]
    6 |     printf("in sum:  sizeof a = %zu\n", sizeof a);
      |                                                ^
decay.c:4:14: note: declared here
    4 | long sum(int a[], size_t n)              // the same as: long sum(int *a, size_t n)
      |          ~~~~^~~
in main: sizeof days = 48
in sum:  sizeof a = 8
sum = 365
Output 4.6. 48 bytes in main, 8 in sum.

This is also why a function can change the elements of an array it receives, with no & at the call: the array’s address is passed by value, and the elements are reached through it.

Definition 4.5 (Row-major order)

A two-dimensional array int g[h][w] is an array of hh rows, each an array of ww elements, stored one row after the other: this is row-major order. Element g[i][j] is element i⋅w+ji \cdot w + j of the block of h⋅wh \cdot w elements.

#include <stdio.h>

int main(void)
{
    int g[3][4];
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 4; j++)
            g[i][j] = 10 * i + j;
    int *flat = &g[0][0];
    for (int k = 0; k < 12; k++)
        printf("%d%c", flat[k], k % 4 == 3 ? '\n' : ' ');
    printf("g[2][1] is element %td of the block\n", &g[2][1] - flat);
    printf("sizeof g = %zu, sizeof g[0] = %zu\n", sizeof g, sizeof g[0]);
    return 0;
}
Listing 4.7. Twelve int in a row code/bachelor-1/04-pointers-and-arrays/listings/rowmajor.c
$ gcc -std=c17 -O2 -Wall -Wextra -o rowmajor rowmajor.c -lm && ./rowmajor
0 1 2 3
10 11 12 13
20 21 22 23
g[2][1] is element 9 of the block
sizeof g = 48, sizeof g[0] = 16
Output 4.7. g[2][1] is element 2⋅4+1=92 \cdot 4 + 1 = 9.

Every compiler lays the rows out this way and lets flat walk the twelve elements. Strictly, though, the standard lets a pointer derived from the row g[0] range only over that row and one past its end; walking further, or subtracting a pointer into row 2, is formally undefined. Portable code indexes g[i][j].

The array g[3][4] of , as written in the source and as stored. The shade marks the row. Walking a row is a stride of 1 in memory; walking a column, a stride of 4.
The array g[3][4] of Listing 4.7, as written in the source and as stored. The shade marks the row. Walking a row is a stride of 1 in memory; walking a column, a stride of 4.

4.4 Out of bounds

Definition 4.6 (Out-of-bounds access)

An out-of-bounds access reads or writes through a pointer, or an index, that does not designate an element of the array it was derived from. C does not check indices: an out-of-bounds access is undefined behaviour, and in practice it reads or writes whatever lies at the computed address.

The commonest one is a loop that runs once too many. In the program below, the fifth write of the loop meant for marks lands in bonus, which on this build is stored just after it; no message, no crash, and a wrong result far from the cause.

#include <stdio.h>

int main(void)
{
    int marks[4] = {12, 15, 9, 14};
    int bonus[4] = {1, 1, 1, 1};
    for (int i = 0; i <= 4; i++)         // one turn too many: i = 4 is outside marks
        marks[i] = 0;
    printf("bonus: %d %d %d %d\n", bonus[0], bonus[1], bonus[2], bonus[3]);
    return 0;
}
Listing 4.8. One write too many code/bachelor-1/04-pointers-and-arrays/listings/neighbour.c
$ gcc -std=c17 -O0 -o neighbour neighbour.c -lm && ./neighbour
bonus: 0 1 1 1
Output 4.8. bonus[0] was changed by a loop that never names it.

The address sanitizer, enabled by -fsanitize=address, places a forbidden zone around every array and checks every access; -g lets it report source lines. The same program, built that way, stops at the bad write and explains it.

$ gcc -std=c17 -O0 -g -fsanitize=address neighbour.c -o neighbour
$ ./neighbour
=================================================================
==1000==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7fffffffec40 at pc 0x55555555542c bp 0x7fffffffebf0 sp 0x7fffffffebe0
WRITE of size 4 at 0x7fffffffec40 thread T0
    #0 0x55555555542b in main ~/session/neighbour.c:10
  This frame has 2 object(s):
    [32, 48) 'marks' (line 7) <== Memory access at offset 48 overflows this variable
    [64, 80) 'bonus' (line 8)
Output 4.9. The first lines of the sanitizer’s report (the rest is a map of the forbidden zones). Some lines are left out.

Read the report from the top: the kind of error (a buffer on the stack overflowed), the access (a write of 4 bytes), the place in the source (line 10, marks[i] = 0), then the variable it overflowed: marks occupies offsets 32 to 48 of main’s frame and the write hit offset 48. As with the undefined-behaviour sanitizer, it can only report the accesses that the run performs.

A null pointer dereference needs no sanitizer: the system stops the program.

#include <stdio.h>

int main(int argc, char **argv)
{
    int *p = NULL;
    if (argc > 5)                        // never true here: p stays NULL
        p = (int *)argv;
    printf("about to read *p\n");
    fflush(stdout);
    printf("*p = %d\n", *p);
    return 0;
}
Listing 4.9. Reading through the null pointer code/bachelor-1/04-pointers-and-arrays/listings/nullderef.c
$ gcc -std=c17 -O2 -Wall -Wextra nullderef.c -o nullderef
$ { ./nullderef; } 2>/dev/null; echo "exit status $?"
about to read *p
exit status 139
Output 4.10. Status 139, as for the stack overflow of Chapter 3: a segmentation fault.

The status 139 reports a segmentation fault: an access to an address that the process has no right to. It is the system’s protection, not the language’s; an out-of-bounds access that stays inside memory the process owns, as in neighbour.c, is not caught at all.

Safe use

Every array access in C is a promise by the programmer that the index is in range. Keep the length beside the array, write loops as i < n, never i <= n, and run the tests with -fsanitize=address. Most of the security flaws in C programs of the last decades started as an out-of-bounds write.

4.5 Pointers to functions

Definition 4.7 (Function pointer)

A function pointer holds the address of a function together with its type: for example int (*f)(int, int) declares f as a pointer to a function taking two int and returning an int. The name of a function converts to a pointer to it, and a call f(6, 7) through the pointer calls the function it points to.

#include <stdio.h>

int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }

int main(void)
{
    int (*op[3])(int, int) = {add, sub, mul};     // three pointers to functions
    const char sign[3] = {'+', '-', '*'};
    for (int k = 0; k < 3; k++)
        printf("12 %c 5 = %d\n", sign[k], op[k](12, 5));
    int (*f)(int, int) = mul;
    printf("f(6, 7) = %d, (*f)(6, 7) = %d\n", f(6, 7), (*f)(6, 7));
    return 0;
}
Listing 4.10. A table of operations code/bachelor-1/04-pointers-and-arrays/listings/ops_table.c
$ gcc -std=c17 -O2 -Wall -Wextra -o ops_table ops_table.c -lm && ./ops_table
12 + 5 = 17
12 - 5 = 7
12 * 5 = 60
f(6, 7) = 42, (*f)(6, 7) = 42
Output 4.11. The operation is chosen by an index at run time.

A function pointer lets a function receive part of its algorithm as an argument. The C library’s sorting function, qsort, sorts an array of any type: it receives the array’s address, the number of elements, the size of one element, and a comparison function that it calls with the addresses of two elements. Since qsort cannot know the type, those addresses arrive as const void *.

Definition 4.8 (Generic pointer)

A pointer to void, or generic pointer, holds an address without saying what is stored there. Any object pointer converts to it and back without loss, with no cast in C. It cannot be dereferenced nor used in pointer arithmetic: it must first be converted to a pointer to a real type.

int increasing(const void *x, const void *y)     // qsort passes the addresses of two elements
{
    int a = *(const int *)x, b = *(const int *)y;
    return (a > b) - (a < b);                    // negative, zero or positive
}

int decreasing(const void *x, const void *y)
{
    return increasing(y, x);
}

int alphabetical(const void *x, const void *y)   // the elements are pointers to characters
{
    return strcmp(*(const char *const *)x, *(const char *const *)y);
}

int main(void)
{
    int born[] = {1967, 1986, 1963, 2002, 2010, 1951, 2007, 1962};
    const char *first[] = {"Emil", "Quinn", "Rosa", "Sami", "Vera", "Nils", "Caio", "Farid"};
    size_t n = sizeof born / sizeof born[0];
    qsort(born, n, sizeof born[0], increasing);
    for (size_t i = 0; i < n; i++)
        printf("%d%c", born[i], i + 1 < n ? ' ' : '\n');
    qsort(born, n, sizeof born[0], decreasing);
    for (size_t i = 0; i < n; i++)
        printf("%d%c", born[i], i + 1 < n ? ' ' : '\n');
    qsort(first, n, sizeof first[0], alphabetical);
    for (size_t i = 0; i < n; i++)
        printf("%s%c", first[i], i + 1 < n ? ' ' : '\n');
    return 0;
Listing 4.11. Three orders for qsort, three comparators code/bachelor-1/04-pointers-and-arrays/listings/sort_people.c
$ gcc -std=c17 -O2 -Wall -Wextra -o sort_people sort_people.c -lm && ./sort_people
1951 1962 1963 1967 1986 2002 2007 2010
2010 2007 2002 1986 1967 1963 1962 1951
Caio Emil Farid Nils Quinn Rosa Sami Vera
Output 4.12. Birth years of eight people of the town, then their first names, in three orders.

A comparator returns a negative number, zero or a positive number as its first argument comes before, with or after the second. The expression (a > b) - (a < b) computes exactly that without the subtraction a - b, which could overflow. To sort the names, the elements are pointers to characters; the comparator receives the addresses of two of them, hence the two levels of pointer in *(const char *const *)x. Strings are the subject of Chapter 6, and Chapter 5 uses void * at every step.

History — Pointers in the hardware

C’s pointers are a thin layer over the machine. The PDP-11, on which C grew up, addressed memory byte by byte and had instructions that read through a register and then advanced it by the size of the item read, which made *p++ a single instruction. BCPL and B, C’s ancestors, had a single type, the machine word; C added types to pointers so that p + 1 could step by the size of the element, whatever it was.

4.6 Exercises

Exercise 4.1 ★

Predict the line printed, following the pointers one statement at a time.

#include <stdio.h>

int main(void)
{
    int a = 1, b = 2;
    int *p = &a, *q = &b;
    *p = *q + 10;
    p = q;
    *p = *p * 3;
    q = &a;
    *q = *q - *p;
    printf("a = %d, b = %d, *p = %d, *q = %d\n", a, b, *p, *q);
    return 0;
}
Listing 4.12. Follow the pointers code/bachelor-1/04-pointers-and-arrays/listings/exo_ptrs.c
Solution

Solution of Exercise 4.1.

*p = *q + 10 writes 2+102 + 10 into a; p = q makes p point to b; *p = *p * 3 makes b 6; q = &a; *q = *q - *p makes a 12−6=612 - 6 = 6. Now p points to b and q to a, both holding 6.

$ gcc -std=c17 -O2 -Wall -Wextra -o exo_ptrs exo_ptrs.c -lm && ./exo_ptrs
a = 6, b = 6, *p = 6, *q = 6
Output 4.17. The output.

Exercise 4.2 ★

Draw the memory at the end of main, as in the figures of this chapter: the array, the three pointers, and an arrow for each pointer. What does main return?

int main(void)
{
    int days[3] = {31, 28, 31};
    int *first = days;
    int *last = &days[2];
    int **which = &last;
    *last = 30;
    *which = first + 1;
    return *last;
}
Listing 4.13. A pointer to a pointer code/bachelor-1/04-pointers-and-arrays/listings/exo_diagram.c
Solution

Solution of Exercise 4.2.

days holds 31, 28, 30 (the third element was changed through last). first points to days[0]. which points to last, and *which = first + 1 changed last, which now points to days[1]. So three arrows: first to days[0], last to days[1], which to last. main returns *last, that is 28.

Exercise 4.3 ★

Predict the four values printed (a double occupies 8 bytes).

#include <stdio.h>

int main(void)
{
    double t[6] = {2.5, -1.0, 4.0, 0.5, 3.5, 1.5};
    double *p = t + 1, *q = &t[5];
    printf("%td %td %.1f %.1f\n", q - p, (char *)q - (char *)p, *(p + 2), p[-1]);
    return 0;
}
Listing 4.14. Pointers into an array of double code/bachelor-1/04-pointers-and-arrays/listings/exo_diff.c
Solution

Solution of Exercise 4.3.

q - p =5−1=4= 5 - 1 = 4 elements, that is 4×8=324 \times 8 = 32 bytes; *(p + 2) is t[3], 0.5; p[-1] is *(p - 1), that is t[0], 2.5 (allowed: p - 1 is still inside the array).

$ gcc -std=c17 -O2 -Wall -Wextra -o exo_diff exo_diff.c -lm && ./exo_diff
4 32 0.5 2.5
Output 4.18. The output.

Exercise 4.4 ★

What does this program print, and why does length not compute the length? Rewrite length’s caller so that the length is computed where it can be.

#include <stdio.h>

size_t length(const double values[])
{
    return sizeof values / sizeof values[0];
}

int main(void)
{
    double values[10] = {0};
    printf("in main: %zu, in length: %zu\n", sizeof values / sizeof values[0], length(values));
    return 0;
}
Listing 4.15. The length, computed twice code/bachelor-1/04-pointers-and-arrays/listings/exo_sizeof.c
Solution

Solution of Exercise 4.4.

$ gcc -std=c17 -O2 -Wall -Wextra -o exo_sizeof exo_sizeof.c -lm && ./exo_sizeof
exo_sizeof.c: In function 'length':
exo_sizeof.c:6:19: warning: 'sizeof' on array function parameter 'values' will return size of 'const double *' [-Wsizeof-array-argument]
    6 |     return sizeof values / sizeof values[0];
      |                   ^~~~~~
exo_sizeof.c:4:28: note: declared here
    4 | size_t length(const double values[])
      |               ~~~~~~~~~~~~~^~~~~~~~
in main: 10, in length: 1
Output 4.19. 10 in main, 1 in length.

In length, values is a pointer: 8/8=18 / 8 = 1. Only where the array itself is in scope does sizeof see its 80 bytes. Compute size_t n = sizeof values / sizeof values[0]; in main and pass n to every function that needs the length.

Exercise 4.5 ★★

Explain the warning below. What would scanf do with the value it received if the program ran, and why might it crash or might not?

#include <stdio.h>

int main(void)
{
    int n = 0;
    if (scanf("%d", n) == 1)
        printf("read %d\n", n);
    return 0;
}
Listing 4.16. Reading a number, the wrong way code/bachelor-1/04-pointers-and-arrays/listings/exo_scanf.c
$ gcc -std=c17 -O2 -Wall -Wextra -c exo_scanf.c
exo_scanf.c: In function 'main':
exo_scanf.c:7:17: warning: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Wformat=]
    7 |     if (scanf("%d", n) == 1)
      |                ~^   ~
      |                 |   |
      |                 |   int
      |                 int *
Output 4.13. The compiler’s warning.
Solution

Solution of Exercise 4.5.

scanf expects, for %d, the address of an int; it received the value of n, an int, which it would take for an address: here 0, so it would try to store the number at address 0 and the system would stop the program. Had n held another value, scanf would have written the number at whatever address that value names: a crash if the address is not the program’s, a silent corruption if it is. Passing an argument of the wrong type to scanf is undefined behaviour; the format check of -Wall catches it.

Exercise 4.6 ★★

The program below was built with the address sanitizer. Read the report, give the bug and its fix, and say what the program would have printed without the sanitizer, in the best case.

#include <stdio.h>

double rain[12] = {48.0, 39.5, 41.0, 52.5, 60.0, 45.5, 30.0, 35.5, 50.0, 66.0, 71.5, 58.0};

int main(void)
{
    int n = 12;
    double total = 0;
    for (int i = 0; i <= n; i++)
        total += rain[i];
    printf("average %.2f mm\n", total / n);
    return 0;
}
Listing 4.17. The average rainfall code/bachelor-1/04-pointers-and-arrays/listings/exo_loop.c
$ gcc -std=c17 -O0 -g -fsanitize=address exo_loop.c -o exo_loop
$ ./exo_loop
=================================================================
==1000==ERROR: AddressSanitizer: global-buffer-overflow on address 0x555555558080 at pc 0x555555555242 bp 0x7fffffffec90 sp 0x7fffffffec80
READ of size 8 at 0x555555558080 thread T0
    #0 0x555555555241 in main ~/session/exo_loop.c:12
0x555555558080 is located 0 bytes to the right of global variable 'rain' defined in 'exo_loop.c:5:8' (0x555555558020) of size 96
SUMMARY: AddressSanitizer: global-buffer-overflow ~/session/exo_loop.c:12 in main
Output 4.14. The first lines of the report. Some lines are left out.
Solution

Solution of Exercise 4.6.

The loop runs for i=0,…,12i = 0, \dots, 12 and reads rain[12], one element past the end of the global array of 12 double (96 bytes): a global buffer overflow, a read of 8 bytes. The fix is i < n. Without the sanitizer, the program would read whatever follows rain in memory; in the best case it is the value 0.0, and the program prints the right average, 597.5/12≈49.79597.5 / 12 \approx 49.79 mm, hiding the bug until the day the memory after rain holds something else.

Exercise 4.7 ★★

Write int min_max(const int *a, size_t n, int *min, int *max), which stores the smallest and the largest element of a[0..n-1] and returns 0, or returns −1-1 without storing anything when n is 0.

Solution

Solution of Exercise 4.7.

int min_max(const int *a, size_t n, int *min, int *max)
{
    if (n == 0)
        return -1;
    int lo = a[0], hi = a[0];
    for (size_t i = 1; i < n; i++) {
        if (a[i] < lo)
            lo = a[i];
        if (a[i] > hi)
            hi = a[i];
    }
    *min = lo;
    *max = hi;
    return 0;
}
One pass, two results code/bachelor-1/04-pointers-and-arrays/exercises/minmax.c

The results go into local variables first and are stored only at the end, so nothing is stored when n is 0. The test is tests/minmax_test.c.

Exercise 4.8 ★★

Write size_t reverse(int *a, size_t n), which reverses an array in place with two pointers, one moving forwards from the start and one backwards from the end, and returns the number of swaps it made.

Solution

Solution of Exercise 4.8.

size_t reverse(int *a, size_t n)
{
    if (n < 2)
        return 0;
    size_t swaps = 0;
    int *left = a, *right = a + n - 1;
    while (left < right) {
        int t = *left;
        *left = *right;
        *right = t;
        left++;
        right--;
        swaps++;
    }
    return swaps;
}
Two pointers that meet in the middle code/bachelor-1/04-pointers-and-arrays/exercises/reverse.c

For n<2n < 2 there is nothing to do, and a + n - 1 must not be formed when n=0n = 0 (it would point before the array). The test tests/reverse_test.c checks every n≤9n \leq 9.

Exercise 4.9 ★★

Predict what the program prints, and explain from the definition of a[i] why 2[a] compiles.

#include <stdio.h>

int main(void)
{
    int a[4] = {7, 8, 9, 10};
    printf("%d %d %d %d\n", a[2], 2[a], *(a + 2), *(2 + a));
    printf("%c\n", "pointer"[3]);
    return 0;
}
Listing 4.18. a[2] and 2[a] code/bachelor-1/04-pointers-and-arrays/listings/exo_index.c
Solution

Solution of Exercise 4.9.

$ gcc -std=c17 -O2 -Wall -Wextra -o exo_index exo_index.c -lm && ./exo_index
9 9 9 9
n
Output 4.20. The output.

a[2] is by definition *(a + 2), and 2[a] is *(2 + a): addition of a pointer and an integer is commutative, so both are the same element. A string literal is an array of characters, so "pointer"[3] is its fourth character, n. Nobody should write 2[a].

Exercise 4.10 ★★★

Prove that the two-pointer reversal of Exercise 4.8 is correct and makes exactly ⌊n/2⌋\lfloor n/2 \rfloor swaps. State the invariant of its loop in terms of left - a and right - a.

Solution

Solution of Exercise 4.10.

Write LL = left - a and RR = right - a. Invariant, at each test of the loop: L+R=n−1L + R = n - 1; the elements at positions <L< L and >R> R hold their final values (position kk holds the original element n−1−kn - 1 - k); the positions from LL to RR hold their original elements. Initially L=0L = 0, R=n−1R = n - 1: true. A turn with L<RL < R exchanges positions LL and R=n−1−LR = n - 1 - L, which puts both final values in place, then LL grows and RR shrinks by 1: true again. The loop stops when L≥RL \geq R; then every position except possibly L=RL = R, the middle one (whose final element is its own), is settled: the array is reversed. The turns are those with L<n−1−LL < n - 1 - L, that is L=0,1,…L = 0, 1, \dots while 2L<n−12L < n - 1: there are ⌈(n−1)/2⌉=⌊n/2⌋\lceil (n-1)/2 \rceil = \lfloor n/2 \rfloor of them, one swap each.

Exercise 4.11 ★★★

Write generic_max(const void *base, size_t n, size_t size, int (*cmp)(const void *, const void *)), which returns the address of a largest element of an array of any type, compared by cmp with the same contract as for qsort, or NULL when n is 0. Why must it convert base to a pointer to char?

Solution

Solution of Exercise 4.11.

const void *generic_max(const void *base, size_t n, size_t size,
                        int (*cmp)(const void *, const void *))
{
    if (n == 0)
        return NULL;
    const char *bytes = base;            // char: pointer arithmetic counts bytes
    const char *best = bytes;
    for (size_t i = 1; i < n; i++) {
        const char *element = bytes + i * size;
        if (cmp(element, best) > 0)
            best = element;
    }
    return best;
}
The largest element of any array code/bachelor-1/04-pointers-and-arrays/exercises/generic_max.c

Pointer arithmetic is not defined on void *, since the size of the element is unknown. A pointer to char counts in bytes, the size of a char being 1 by definition, so bytes + i * size is the address of element ii. The test tests/generic_max_test.c uses it on int, double and pointers to characters.

Exercise 4.12 ★★★

In an array of nn elements, the valid pointers are a + 0 to a + n (one past the end included). Count the pairs (p,q)(p, q) of valid pointers with p≤qp \leq q, and prove your count. What does each such pair describe?

Solution

Solution of Exercise 4.12.

The valid pointers are n+1n + 1 positions. Pairs with p<qp < q: choose two distinct positions, (n+12)\binom{n+1}{2} ways; pairs with p=qp = q: n+1n + 1. In all (n+12)+(n+1)=(n+1)(n+2)/2\binom{n+1}{2} + (n+1) = (n+1)(n+2)/2. Each pair describes a slice of the array, the elements from pp included to qq excluded, with q−pq - p elements; the n+1n + 1 pairs with p=qp = q are the empty slices. The test tests/test_pointer_pairs.py counts them for n<30n < 30.

4.7 Problem: A spreadsheet in a flat array

Problem 4.1

Weekend problem — A spreadsheet in a flat array

A small spreadsheet program stores a grid of hh rows and ww columns of whole numbers in one block of h⋅wh \cdot w int, row after row. The module grid.c computes the address of a cell, sums along a row and a column, and transposes a square grid in place; sheet.c tries it on a 4×44 \times 4 grid. A colleague’s first transpose, transpose_bug.c, was built with the address sanitizer.

int *cell(int *g, int w, int i, int j)
{
    return g + i * w + j;
}

long row_sum(const int *g, int w, int i)
{
    long s = 0;
    for (const int *p = g + i * w; p < g + (i + 1) * w; p++)
        s += *p;
    return s;
}

long col_sum(const int *g, int w, int h, int j)
{
    long s = 0;
    for (const int *p = g + j; p < g + h * w; p += w)
        s += *p;
    return s;
}

long transpose(int *g, int n)
{
    long swaps = 0;
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++) {            // above the diagonal only
            int t = g[i * n + j];
            g[i * n + j] = g[j * n + i];
            g[j * n + i] = t;
            swaps++;
        }
    return swaps;
}
Listing 4.19. The module: the index map, two walks, the transpose code/bachelor-1/04-pointers-and-arrays/listings/grid.c
$ gcc -std=c17 -O2 -Wall -Wextra -o sheet sheet.c grid.c -lm && ./sheet
  0   1   2   3
 10  11  12  13
 20  21  22  23
 30  31  32  33
row 2 sums to 86, column 3 to 72
after the transpose (6 swaps):
  0  10  20  30
  1  11  21  31
  2  12  22  32
  3  13  23  33
n = 1: 0 swaps
n = 2: 1 swaps
n = 3: 3 swaps
n = 4: 6 swaps
n = 5: 10 swaps
n = 6: 15 swaps
n = 7: 21 swaps
n = 8: 28 swaps
Output 4.15. The grid, its sums, its transpose, and the swaps for n=1n = 1 to 8.
void transpose(int *g, int n)
{
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j <= n; j++) {           // <= : one column too far
            int t = g[i * n + j];
            g[i * n + j] = g[j * n + i];
            g[j * n + i] = t;
        }
}
Listing 4.20. The colleague’s transpose code/bachelor-1/04-pointers-and-arrays/listings/transpose_bug.c
$ gcc -std=c17 -O0 -g -fsanitize=address transpose_bug.c -o transpose_bug
$ ./transpose_bug
=================================================================
==1000==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7fffffffec34 at pc 0x55555555536a bp 0x7fffffffeb90 sp 0x7fffffffeb80
READ of size 4 at 0x7fffffffec34 thread T0
    #0 0x555555555369 in transpose ~/session/transpose_bug.c:10
    #1 0x555555555704 in main ~/session/transpose_bug.c:18
  This frame has 1 object(s):
    [48, 84) 'g' (line 17) <== Memory access at offset 84 overflows this variable
Output 4.16. The first lines of the sanitizer’s report. Some lines are left out.

Part I — The index map.

  1. Let f(i,j)=iw+jf(i, j) = i w + j for 0≤i<h0 \leq i < h, 0≤j<w0 \leq j < w. Compute f(2,1)f(2, 1) and f(3,3)f(3, 3) for w=4w = 4.
  2. Prove that ff takes its values in [0,hw)[0, hw).
  3. Prove that ff is injective. (Hint: if iw+j=i′w+j′iw + j = i'w + j', look at the remainder of the division by ww.)
  4. Deduce that ff is a bijection onto [0,hw)[0, hw), and give its inverse with / and %.
  5. Why does cell return g + i * w + j and not g + (i * w + j) * sizeof(int)?
  6. A grid of h=50 000h = 50\,000 rows and w=50 000w = 50\,000 columns: can i * w + j be computed in int? What type should the index have?

Part II — Walking with pointers.

  1. In row_sum, which cells does p visit, and what is the last value of p, which is never dereferenced?
  2. In col_sum, by how many elements does p advance at each step? By how many bytes?
  3. Prove that col_sum visits exactly the hh cells of column jj.
  4. The last value of p in col_sum is g + h * w + j. Is it allowed to compute it? Rewrite the loop with an index so that no pointer beyond the end is formed.
  5. Check the printed sums: row 2 and column 3 of the grid 10 * i + j.
  6. Give, for the grid 10 * i + j with h=w=nh = w = n, the formulas of row sum ii and column sum jj.

Part III — The transpose in place.

  1. Show that exchanging g[i * n + j] and g[j * n + i] for every pair with i<ji < j transposes the grid.
  2. Why must the loop not also run over the pairs with i>ji > j? What would the grid be after it?
  3. Count the swaps: prove that there are exactly n(n−1)/2n(n-1)/2.
  4. Check that count against the output for n=1n = 1 to 8.
  5. Show that the diagonal cells (i,i)(i, i) never move, and that each other cell moves exactly once.
  6. How many swaps would a transpose into a second grid need, and how much extra memory? Compare.

Part IV — The colleague’s bug.

  1. For n=3n = 3 and i=0i = 0, list the pairs of indices that the buggy loop exchanges.
  2. Which of them is out of the array, and why does the sanitizer report a read of 4 bytes at offset 84 of the frame, given that g occupies offsets 48 to 84?
  3. Without the sanitizer, which two cells does the exchange with j=nj = n touch, for i<n−1i < n - 1? Which of them lies inside the array, and what does it hold?
  4. For n=1n = 1, which exchange does the buggy loop make? Explain why a test on a 1×11 \times 1 grid, without the sanitizer, would not notice the bug.
  5. Which line of the report lets you find the faulty line of the source, and which tells you that the caller is main?
  6. State the named result of the problem: the in-place transpose makes exactly n(n−1)/2n(n-1)/2 swaps, with the range of pairs that achieves it and the counts measured.
Solution

Solution of Problem 4.1.

1. f(2,1)=9f(2, 1) = 9, f(3,3)=15f(3, 3) = 15.

2. f(i,j)≥0f(i, j) \geq 0, and f(i,j)≤(h−1)w+(w−1)=hw−1f(i, j) \leq (h - 1)w + (w - 1) = hw - 1.

3. If iw+j=i′w+j′iw + j = i'w + j' with 0≤j,j′<w0 \leq j, j' < w, both sides have the same remainder when divided by ww: j=j′j = j'; then iw=i′wiw = i'w and i=i′i = i'.

4. An injective map from a set of hwhw elements into a set of hwhw elements is a bijection. Its inverse is k↦(k/w,k mod w)k \mapsto (k / w, k \bmod w), written (k / w, k % w) in C.

5. Pointer arithmetic counts in elements: g + k is already 4k4k bytes after g. Multiplying by sizeof(int) would go four times too far.

6. 50 0002=2.5×109>231−150\,000^2 = 2.5 \times 10^9 > 2^{31} - 1: i * w overflows int. The index should be computed in size_t (or another 64-bit type), and so should the sizes.

7. g + i*w to g + i*w + w - 1, the ww cells of row ii; the final value g + (i+1)*w is one past the row: the first cell of the next row, or one past the end of the grid for the last row.

8. ww elements, that is 4w4w bytes (16 here).

9. p takes the values g + j + k*w for k=0,1,…k = 0, 1, \dots while j+kw<hwj + kw < hw. Since 0≤j<w0 \leq j < w, that is k≤h−1k \leq h - 1: the cells f(0,j),…,f(h−1,j)f(0, j), \dots, f(h-1, j), which are column jj, each once.

10. For j>0j > 0, g + h*w + j lies beyond the one-past-the-end position g + h*w: forming it is undefined behaviour, even unread. With an index: for (int k = 0; k < h; k++) s += g[k * w + j];.

11. Row 2: 20+21+22+23=8620 + 21 + 22 + 23 = 86; column 3: 3+13+23+33=723 + 13 + 23 + 33 = 72.

12. Row ii: ∑j(10i+j)=10in+n(n−1)/2\sum_j (10i + j) = 10in + n(n-1)/2. Column jj: ∑i(10i+j)=5n(n−1)+nj\sum_i (10i + j) = 5n(n-1) + nj.

13. The transpose TT has T(i,j)=G(j,i)T(i, j) = G(j, i). The cells off the diagonal fall into pairs {(i,j),(j,i)}\{(i, j), (j, i)\} with i<ji < j; one exchange puts both cells of a pair right, the pairs are disjoint, and the diagonal is already right.

14. Each pair would be exchanged twice, once as (i,j)(i, j) and once as (j,i)(j, i): the grid would come back unchanged.

15. One swap per pair i<ji < j of indices among nn: (n2)=n(n−1)/2\binom{n}{2} = n(n-1)/2. Or: row ii contributes n−1−in - 1 - i swaps, and ∑i=0n−1(n−1−i)=n(n−1)/2\sum_{i=0}^{n-1} (n - 1 - i) = n(n-1)/2.

16. 0,1,3,6,10,15,21,280, 1, 3, 6, 10, 15, 21, 28 for n=1,…,8n = 1, \dots, 8: the printed values.

17. A diagonal cell has i=ji = j, and the loop only reaches pairs with i<ji < j. An off-diagonal cell (i,j)(i, j) belongs to exactly one pair, {(min⁡,max⁡)}\{(\min, \max)\}, so it moves once.

18. A copy writes n2n^2 cells into a second grid of n2n^2 int; the transpose in place makes n(n−1)/2n(n-1)/2 swaps (three assignments each) with one extra int. For n=1000n = 1000: 4 MB of extra memory against 4 bytes.

19. j=1,2,3j = 1, 2, 3: indices (1,3)(1, 3), (2,6)(2, 6) and (3,9)(3, 9).

20. Index 9 does not exist in an array of 9 elements. It lies 9×4=369 \times 4 = 36 bytes after the start of g, at offset 48+36=8448 + 36 = 84, the first byte past g. Line 10 is g[i * n + j] = g[j * n + i];, which reads g[9]: a read of 4 bytes, reported before any write out of bounds happens.

21. g[i*n + n], which is g[(i+1)*n], the first cell of row i+1i + 1: inside the array, holding a value of the grid that the loop should not touch; and g[n*n + i], outside the array.

22. For n=1n = 1, i=0i = 0 and j=1j = 1: the loop exchanges g[1] with g[1], a cell outside the array, with itself. Reading a value and writing it back changes nothing visible, so the 1×11 \times 1 grid comes out right and the test passes; only the sanitizer would report the access.

23. Frame #0 gives the faulty line, transpose_bug.c:10 in transpose; frame #1 gives the caller, main at line 18.

24. The in-place transpose makes exactly n(n−1)/2n(n-1)/2 swaps: it exchanges g[i*n + j] and g[j*n + i] for the pairs 0≤i<j<n0 \leq i < j < n only, which moves every off-diagonal cell once and leaves the diagonal in place; the run counted 0,1,3,6,10,15,21,280, 1, 3, 6, 10, 15, 21, 28 swaps for n=1n = 1 to 8, and the colleague’s j <= n was caught by the sanitizer at its first access past the grid.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো