এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: 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;
}
$ 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
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.
*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;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o swap_ptr swap_ptr.c -lm && ./swap_ptr
after swap: x = 2, y = 1
x and y are exchanged.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;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o divmod divmod.c -lm && ./divmod
2026 = 7 * 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;
}
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
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 of an array, p + k points to element : pointer arithmetic counts in elements, not bytes, so the address grows by 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;
}
$ 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
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.
int. The pointer a + k designates element , 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;
}
$ 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
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 rows, each an array of elements, stored one row after the other: this is row-major order. Element g[i][j] is element of the block of 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;
}
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
g[2][1] is element .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].
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;
}
$ gcc -std=c17 -O0 -o neighbour neighbour.c -lm && ./neighbour
bonus: 0 1 1 1
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)
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;
}
$ gcc -std=c17 -O2 -Wall -Wextra nullderef.c -o nullderef
$ { ./nullderef; } 2>/dev/null; echo "exit status $?"
about to read *p
exit status 139
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;
}
$ 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
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;
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
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;
}
Solution
Solution of Exercise 4.1.
*p = *q + 10 writes into a; p = q makes p point to b; *p = *p * 3 makes b 6; q = &a; *q = *q - *p makes a . 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
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;
}
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;
}
double code/bachelor-1/04-pointers-and-arrays/listings/exo_diff.cSolution
Solution of Exercise 4.3.
q - p elements, that is 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
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;
}
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
main, 1 in length.In length, values is a pointer: . 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;
}
$ 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 *
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;
}
$ 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
Solution
Solution of Exercise 4.6.
The loop runs for 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, 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 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;
}
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;
}
For there is nothing to do, and a + n - 1 must not be formed when (it would point before the array). The test tests/reverse_test.c checks every .
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;
}
a[2] and 2[a] code/bachelor-1/04-pointers-and-arrays/listings/exo_index.cSolution
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
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 swaps. State the invariant of its loop in terms of left - a and right - a.
Solution
Solution of Exercise 4.10.
Write = left - a and = right - a. Invariant, at each test of the loop: ; the elements at positions and hold their final values (position holds the original element ); the positions from to hold their original elements. Initially , : true. A turn with exchanges positions and , which puts both final values in place, then grows and shrinks by 1: true again. The loop stops when ; then every position except possibly , the middle one (whose final element is its own), is settled: the array is reversed. The turns are those with , that is while : there are 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;
}
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 . The test tests/generic_max_test.c uses it on int, double and pointers to characters.
Exercise 4.12 ★★★
In an array of elements, the valid pointers are a + 0 to a + n (one past the end included). Count the pairs of valid pointers with , and prove your count. What does each such pair describe?
Solution
Solution of Exercise 4.12.
The valid pointers are positions. Pairs with : choose two distinct positions, ways; pairs with : . In all . Each pair describes a slice of the array, the elements from included to excluded, with elements; the pairs with are the empty slices. The test tests/test_pointer_pairs.py counts them for .
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 rows and columns of whole numbers in one block of 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 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;
}
$ 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
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;
}
}
$ 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
Part I — The index map.
- Let for , . Compute and for .
- Prove that takes its values in .
- Prove that is injective. (Hint: if , look at the remainder of the division by .)
- Deduce that is a bijection onto , and give its inverse with
/and%. - Why does
cellreturng + i * w + jand notg + (i * w + j) * sizeof(int)? - A grid of rows and columns: can
i * w + jbe computed inint? What type should the index have?
Part II — Walking with pointers.
- In
row_sum, which cells doespvisit, and what is the last value ofp, which is never dereferenced? - In
col_sum, by how many elements doespadvance at each step? By how many bytes? - Prove that
col_sumvisits exactly the cells of column . - The last value of
pincol_sumisg + h * w + j. Is it allowed to compute it? Rewrite the loop with an index so that no pointer beyond the end is formed. - Check the printed sums: row 2 and column 3 of the grid
10 * i + j. - Give, for the grid
10 * i + jwith , the formulas of row sum and column sum .
Part III — The transpose in place.
- Show that exchanging
g[i * n + j]andg[j * n + i]for every pair with transposes the grid. - Why must the loop not also run over the pairs with ? What would the grid be after it?
- Count the swaps: prove that there are exactly .
- Check that count against the output for to 8.
- Show that the diagonal cells never move, and that each other cell moves exactly once.
- How many swaps would a transpose into a second grid need, and how much extra memory? Compare.
Part IV — The colleague’s bug.
- For and , list the pairs of indices that the buggy loop exchanges.
- 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
goccupies offsets 48 to 84? - Without the sanitizer, which two cells does the exchange with touch, for ? Which of them lies inside the array, and what does it hold?
- For , which exchange does the buggy loop make? Explain why a test on a grid, without the sanitizer, would not notice the bug.
- Which line of the report lets you find the faulty line of the source, and which tells you that the caller is
main? - State the named result of the problem: the in-place transpose makes exactly swaps, with the range of pairs that achieves it and the counts measured.
Solution
Solution of Problem 4.1.
1. , .
2. , and .
3. If with , both sides have the same remainder when divided by : ; then and .
4. An injective map from a set of elements into a set of elements is a bijection. Its inverse is , written (k / w, k % w) in C.
5. Pointer arithmetic counts in elements: g + k is already bytes after g. Multiplying by sizeof(int) would go four times too far.
6. : 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 cells of row ; 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. elements, that is bytes (16 here).
9. p takes the values g + j + k*w for while . Since , that is : the cells , which are column , each once.
10. For , 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: ; column 3: .
12. Row : . Column : .
13. The transpose has . The cells off the diagonal fall into pairs with ; 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 and once as : the grid would come back unchanged.
15. One swap per pair of indices among : . Or: row contributes swaps, and .
16. for : the printed values.
17. A diagonal cell has , and the loop only reaches pairs with . An off-diagonal cell belongs to exactly one pair, , so it moves once.
18. A copy writes cells into a second grid of int; the transpose in place makes swaps (three assignments each) with one extra int. For : 4 MB of extra memory against 4 bytes.
19. : indices , and .
20. Index 9 does not exist in an array of 9 elements. It lies bytes after the start of g, at offset , 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 : 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 , and : 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 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 swaps: it exchanges g[i*n + j] and g[j*n + i] for the pairs only, which moves every off-diagonal cell once and leaves the diagonal in place; the run counted swaps for to 8, and the colleague’s j <= n was caught by the sanitizer at its first access past the grid.