Class 16 — Tuesday, October 20
Quiz 6 first, on Brightspace: one attempt now. The second comes near the end of class, when it is announced. Then the Opening Journal: its prompt is in the announcements.
1 One flag for memory mistakes
Today every program is built with two more flags:
-g puts line numbers into the program, and -fsanitize=address makes it stop at a memory mistake and say what the mistake was and on which line.
Shorter: save the course Makefile in the folder with your programs. Then make run-range builds range.c with both flags and runs it, and make entr-range does that again on every save. More on it on the command line page.
1.1 range, with 8 and 3
Thursday’s range, reading its two numbers:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
// returns a new array holding start, start + 1, ..., end - 1; the caller frees it
int * range(int start, int end) {
int * a = malloc(sizeof(int) * (end - start));
assert(a != NULL);
int value = start;
for (int * p = a; p < a + (end - start); p++) {
*p = value;
value++;
}
return a;
}
int main() {
int start;
int end;
printf("start and end: ");
scanf("%d %d", &start, &end);
int * r = range(start, end);
printf("%d\n", *r);
free(r);
}On Thursday the assert stopped 8 3. Build it with the flag, run it, and type 8 3: what stops it now, and which line does it name?
1.2 Three ways to get ownership wrong
Every piece of memory from malloc has one owner: the part of the program that must free it.
malloc protocol
malloctakes the size in bytes:sizeof(int) * nfornints, andstrlen(s) + 1for a copy of the strings, the+ 1for its'\0'.The
assertchecks the address againstNULLbefore it is used.And the memory’s owner gives it back with
free, once, after its last use.
The comment above a function says who owns the address it returns. In the program below, each comment ends in one of two ways:
- the caller frees it: the function made new memory, and you must free it.
- points into s: the address is inside
s, so it is not new memory. It is freed whensis freed, and you can use it only until then.
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// returns a new string holding the same characters as s; the caller frees it
char * copy(char * s) {
char * c = malloc(strlen(s) + 1);
assert(c != NULL);
strcpy(c, s);
return c;
}
// returns whichever of a and b is longer; points into a or b
char * longer(char * a, char * b) {
if (strlen(a) >= strlen(b)) {
return a;
}
return b;
}
// returns the address of the first c in s, or NULL; points into s
char * find_char(char * s, char c) {
for (char * p = s; *p != '\0'; p++) {
if (*p == c) {
return p;
}
}
return NULL;
}
// 1: nobody frees it
void nobody() {
printf("%s\n", copy("hello"));
}
// 2: two free it
void two() {
char * a = copy("pointer");
char * b = copy("point");
char * l = longer(a, b);
printf("%s\n", l);
free(a);
free(b);
free(l);
}
// 3: used after its owner frees it
void after_free() {
char * s = copy("pointer");
char * p = find_char(s, 'n');
free(s);
printf("%s\n", p);
}
int main() {
int which;
printf("mistake 1, 2 or 3: ");
scanf("%d", &which);
if (which == 1) {
nobody();
} else if (which == 2) {
two();
} else if (which == 3) {
after_free();
}
}Save it as owners.c and build it with the flag. Nobody runs it until it is announced. Predict first, in the Journal, for each of 1, 2 and 3: what is wrong in the function it runs, and will the flag report it or stay quiet? Then run it three times, typing 1, then 2, then 3.
2 Owning one string at a time, in pairs
- The navigator (not typing) says the examples first. Then they say the steps the program takes.
- The driver types the above, and decides how each step becomes C.
- If either of you is stuck, drop the roles for a minute and talk it over.
- Swap at every program.
Build everything today with -g -fsanitize=address: with the course Makefile from section 1, keep make entr-first running in a second terminal.
2.1 first.c
Write a program that reads words until the input ends and prints the one that comes first alphabetically. The word it keeps lives in memory it owns.
char word[WORD];, with#define WORD 100, andwhile (scanf("%99s", word) == 1)read one word at a time into the same array, which is why the best word so far needs a copy of its own:char * best.strcmp(word, best) < 0is true whenwordcomes first.beststarts asNULL, meaning no word yet. When a better word arrives,freethe old copy and keep acopyof the new one;free(NULL)does nothing, so the first word needs no special case.- At the end, print
bestand free it, or printno wordswhen there were none.
Make a file words.txt holding pointer malloc free address string, then run ./first < words.txt. Done when it prints address and the flag reports nothing, and ./first < /dev/null prints no words.
2.2 Your A7 programs, under the flag
A7 is due tomorrow night. Build each of your A7 programs with -g -fsanitize=address and run it as its step says. Done when each one runs with no report. A report names the malloc line of memory that was never freed, or the line that used memory after it was freed.
3 Keep going
For pairs who are done with section 2.
3.1 owners.c, fixed
Change each of the three so that it prints what it printed, and runs with no report from the flag. Done when all three are clean.
3.2 The first word and the last
Change first.c to print the alphabetically last word too. Two strings are now owned at once, first and last, each replaced and freed on its own. Done when ./first < words.txt prints address and string, and the flag reports nothing.
4 Before you leave
- Quiz 6, attempt 2, when it is announced.
- A7 is due Wednesday, October 21, and Thursday is its presentation.
- The Closing Journal: its prompt is in the announcements on Brightspace.