Questions 7–12
7. What does it print?
typedef struct {
int x;
int y;
} Point;
Point a = {1, 2};
Point b = a;
b.x = 5;
printf("%d %d\n", a.x, b.x);
Answer
1 5
b = a copies the whole struct: b is a separate copy, so changing b.x doesn't touch a. (Topic 10)
8. Why doesn't it compile?
void move(Point *p) {
*p.x = 3;
}
Answer
. binds tighter than *, so *p.x means *(p.x), and p is a pointer, not a struct. GCC even suggests: 'p' is a pointer; did you mean to use '->'?. Correct: p->x = 3; (the same as (*p).x = 3;). (Topic 10)
9. What does it print?
The file cities.txt is one line, Kaunas-Vilnius.
char line[8];
while (fgets(line, sizeof line, f) != NULL) {
printf("[%s]\n", line);
}
Answer
[Kaunas-]
[Vilnius]
[
]
fgets reads at most sizeof line - 1 = 7 characters and adds a '\0'. The line (14 letters and a '\n') doesn't fit, so it arrives in three pieces; the last one is just '\n'. Whether the whole line was read shows by whether there is a '\n' at the end. (Topic 11)
10. What's wrong?
FILE *f = fopen("grades.txt", "r");
char line[100];
fgets(line, sizeof line, f);
if (f == NULL) {
printf("No file.\n");
return 1;
}
printf("%s", line);
fclose(f);
Answer
NULL is checked too late: when there's no file, fgets has already got NULL – on Linux the program stops (Segmentation fault), in GitHub CI UBSan stops it first (null pointer passed as argument 3, which is declared to never be null), on MinGW fgets silently returns NULL. Also, fgets's result isn't checked: for an empty file line stays unfilled and garbage is printed. Correct: if (f == NULL) right after fopen, if (fgets(...) == NULL) before using line. (Topic 11)
11. What's wrong?
int *a = malloc(3 * sizeof *a);
if (a == NULL) {
return 1;
}
int *b = a;
free(a);
a = NULL;
b[0] = 1;
Answer
b points at the same block, and it is already freed. a = NULL protects only a, not other pointers to the same block. MinGW (GCC 11) compiles it, and the program will most likely "work". The newer GCC in GitHub CI refuses to compile it: pointer ‘b’ used after ‘free’ [-Werror=use-after-free]. When the pointer is used in another function, the compiler no longer sees it, and ASan stops the running program: heap-use-after-free. (Topic 12)
12. What does it print?
int *p = malloc(100 * sizeof *p);
if (p == NULL) {
return 1;
}
printf("%zu\n", sizeof p / sizeof *p);
free(p);
Answer
It doesn't compile: division 'sizeof (int *) / sizeof (int)' does not compute the number of array elements. Without -Werror it would print 2 (8 bytes / 4), not 100: p is just an address, and only you know how many elements were allocated. That's why a dynamic array always travels with count and capacity. (Topic 12)