Intermediate Study Questions

Programming with C · Part 2 · Weeks 15–28
15 · Pointer Arithmetic and Arrays16 · Pointers as Function Parameters17 · Scope, Lifetime, and Program Memory Layout18 · Recursion19 · Dynamic Memory Allocation20 · Memory Errors and Their Diagnosis21 · Structures22 · Unions, Enumerations, and Type Aliases23 · Program Arguments and Input24 · The Standard Library Toolbox25 · Bit-Level Operations26 · Files and Streams27 · Error Handling Strategies28 · The Preprocessor and Modular Programming
Sercan KÜLCÜ · Giresun University · Computer Engineering

Multiple Choice · Week 15: Pointer Arithmetic and Arrays

Question 1: Reverse Loop With Pointers

A programmer walks an array backwards with the loop below. What is wrong with it?

for (const int *q = values + n - 1; q >= values; q--) {
    printf("%d ", *q);
}

A: forming a pointer before the first element is undefined behavior even if it is never dereferenced. The safe shape is for (q = values + n; q-- > values; ). Option B is false (the first element read is values[n-1]), C is false (< and >= are allowed within one array), and D is false (values[0] is visited).

Output Question · Week 15: Pointer Arithmetic and Arrays

Question 2: Pointer Subtraction And Steps

What does this program print?

#include <stdio.h>
#include <stddef.h>

int main(void)
{
    int v[6] = { 5, 10, 15, 20, 25, 30 };
    int *p = v + 1;
    int *q = v + 5;
    ptrdiff_t d = q - p;

    printf("%td\n", d);
    printf("%d %d\n", *(p + 2), p[3]);
    p += 2;
    printf("%d %td\n", *p, p - v);
    for (const int *r = v + 6; r-- > v; ) {
        printf("%d ", *r);
    }
    putchar('\n');
    return 0;
}
Show answer
4
20 25
20 3
30 25 20 15 10 5 

Pointer subtraction counts elements, not bytes, so q - p is 4. p[3] is *(p + 3), which is v[4]. After p += 2 the pointer is at v[3], so the value is 20 and the distance from v is 3. The countdown loop never forms an address before the array.

Multiple Choice · Week 16: Pointers as Function Parameters

Question 3: Which Statement Compiles

Given the declarations below, exactly one of the statements compiles without an error. Which one?

char buf[8] = "abc";
const char *p = buf;
char * const q = buf;

B: q is a constant pointer to writable characters, so writing through it is fine. A fails because p points to const characters. C fails because the pointer q itself is const. D fails on its second half: q = p assigns to a const pointer (and would also drop the const from the target).

Multiple Choice · Week 17: Scope, Lifetime, and Program Memory Layout

Question 4: Zeroed Global Array Size

A program declares int table[2500000]; at file scope with no initializer, yet its executable file is only a few kilobytes. Why?

C: zero-initialized statics live in .bss. Only the total size is recorded in the executable; the loader reserves and clears that much memory before main runs. .data would have to store the contents, .rodata is for read-only data, and static objects are not taken from the heap.

Output Question · Week 18: Recursion

Question 5: Frames Down And Back Up

What does this program print?

#include <stdio.h>

static void f(int n)
{
    if (n == 0) {
        printf("base ");
        return;
    }
    printf("%d ", n);
    f(n - 1);
    printf("%d ", n);
}

int main(void)
{
    f(3);
    putchar('\n');
    return 0;
}
Show answer
3 2 1 base 1 2 3 

The first printf runs on the way down, so it prints 3, 2, 1 before the base case. Each suspended frame still holds its own n; as the stack unwinds the second printf runs in the reverse order, giving 1, 2, 3.

Classic Question · Week 19: Dynamic Memory Allocation

Question 6: Growing A Block Safely

A growable array is extended with values = realloc(values, new_count * sizeof *values);. What can go wrong, how do you write it correctly, and what must you remember about other pointers into the old block?

Show answer

If realloc fails it returns NULL but leaves the original block allocated. Assigning the result straight to values overwrites the only pointer to that block, so it can never be freed: a leak that happens exactly when memory is short, followed by a null dereference.

Write it with a temporary: int *bigger = realloc(values, new_count * sizeof *values); if (bigger == NULL) { /* values is still valid: free it or report */ } else { values = bigger; }.

Also, realloc may move the block. Any other pointer into the old block (for example a pointer to one element) is then dangling, so such pointers must be recomputed from the new base address.

Multiple Choice · Week 20: Memory Errors and Their Diagnosis

Question 7: Reading A Sanitizer Report

AddressSanitizer reports heap-buffer-overflow, WRITE of size 4, "0 bytes to the right of 40-byte region", and the block was created by malloc(10 * sizeof(int)). What is the most likely defect?

A: the access is a write that begins exactly at the end of the 40-byte block, which is element 10 of a 10-element array. A leak is reported at exit as a leak, a double free is reported as double-free, and a use after free as heap-use-after-free; the error type names the class.

Output Question · Week 21: Structures

Question 8: Structure Copy Versus Pointer

What does this program print?

#include <stdio.h>

typedef struct {
    int x;
    int y;
} Point;

static void move_by_value(Point p)
{
    p.x += 10;
}

static void move_by_pointer(Point *p)
{
    p->x += 10;
}

int main(void)
{
    Point a = { .x = 1, .y = 2 };
    Point b = a;

    move_by_value(a);
    printf("%d %d\n", a.x, a.y);
    move_by_pointer(&a);
    b.y = 9;
    printf("%d %d %d %d\n", a.x, a.y, b.x, b.y);
    return 0;
}
Show answer
1 2
11 2 1 9

Passing a structure by value copies every member, so move_by_value changes only its own copy. move_by_pointer modifies the caller's structure. The assignment Point b = a; makes an independent copy, so changing b.y leaves a alone.

Multiple Choice · Week 22: Unions, Enumerations, and Type Aliases

Question 9: Default In Enum Switch

Why is it usually a mistake to add a default label to a switch over an enumeration type?

A: with no default, -Wswitch lists every enumerator that has no case, so adding a value later points at every site to update. A default label silences that check. It is legal, it has no runtime cost worth mentioning, and it is only chosen when no case matches. Handle the out-of-range value after the switch instead.

Classic Question · Week 22: Unions, Enumerations, and Type Aliases

Question 10: Tagged Union Design

Why is a bare union almost always wrong in an interface, and how does a tagged union fix it? Sketch the declaration and say how a value is read safely.

Show answer

A union stores its members in the same space, and nothing in it records which member was written last. Reading a different member gives an unspecified value, and every caller would have to track the live member by hand.

A tagged union pairs it with an enumeration inside a structure: typedef struct { ValueKind kind; union { int as_int; double as_double; char as_text[24]; } data; } Value;, where ValueKind is VAL_INT, VAL_DOUBLE, VAL_TEXT.

Every access goes through a switch (v->kind) that reads only the member named by the tag. Because the switch is over an enumeration without default, the compiler warns at each site when a new kind is added.

Multiple Choice · Week 23: Program Arguments and Input

Question 11: The End Of argv

A program main(int argc, char *argv[]) is started as ./prog 7. Which statement is guaranteed by the C standard?

B: argv[argc] is a null pointer, which allows for (char **p = argv + 1; *p; p++). In A the pointer after the last argument is that null pointer, not undefined. C is wrong because argv[0] is the program name as invoked, and D is wrong because every argument arrives as a string.

Output Question · Week 23: Program Arguments and Input

Question 12: strtol And The End Pointer

What does this program print?

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>

int main(void)
{
    const char *s;
    char *end;
    long v;

    s = "12abc";
    v = strtol(s, &end, 10);
    printf("%ld [%s] %td\n", v, end, end - s);

    s = "abc";
    v = strtol(s, &end, 10);
    printf("%ld %d\n", v, end == s);

    s = "  -7";
    v = strtol(s, &end, 10);
    printf("%ld %d\n", v, *end == '\0');
    return 0;
}
Show answer
12 [abc] 2
0 1
-7 1

For "12abc" the conversion stops at the first non-digit, so end points at "abc", two characters in. For "abc" nothing is converted: the result is 0 but end == s reveals that it was not a number. In " -7" leading white space and the sign are accepted and end reaches the terminator. This is exactly the information atoi throws away.

Multiple Choice · Week 24: The Standard Library Toolbox

Question 13: Reseeding Inside A Loop

What is the typical symptom of this code?

for (int i = 0; i < 5; i++) {
    srand((unsigned)time(NULL));
    printf("%d ", rand() % 6 + 1);
}

A: srand resets the generator to a state fixed by the seed, and time(NULL) changes only once per second, so within one second every iteration starts the same sequence and takes its first value. Seed once, at program start.

Output Question · Week 25: Bit-Level Operations

Question 14: Flags And Precedence

What does this program print?

#include <stdio.h>

#define FLAG_READ  (1u << 0)
#define FLAG_WRITE (1u << 1)
#define FLAG_EXEC  (1u << 2)

int main(void)
{
    unsigned flags = 0;

    flags |= FLAG_READ | FLAG_EXEC;
    printf("%u\n", flags);
    flags ^= FLAG_READ;
    flags &= ~FLAG_EXEC;
    flags |= FLAG_WRITE;
    printf("%u\n", flags);
    printf("%d\n", (flags & FLAG_WRITE) != 0);
    printf("%d\n", (flags & (FLAG_READ | FLAG_WRITE)) == (FLAG_READ | FLAG_WRITE));
    printf("%u\n", flags & FLAG_WRITE == 0);
    return 0;
}
Show answer
5
2
1
0
0

Set gives 0101 = 5. Toggling READ gives 0100, clearing EXEC gives 0000, and setting WRITE gives 0010 = 2. WRITE is set (1). Comparing against the whole mask tests "all of them", and READ is missing (0). The last line parses as flags & (FLAG_WRITE == 0), that is flags & 0, which is always 0 even though the bit is set; the comparison needs parentheses.

Multiple Choice · Week 26: Files and Streams

Question 15: Short Return From fread

A program calls n = fread(buf, 32, 4, f); and gets n == 3. What does that tell you?

C: fread returns the number of items transferred, not bytes. A value smaller than the requested count means end of file or an error; use feof and ferror afterwards to tell them apart. The three items that were read are valid.

Classic Question · Week 26: Files and Streams

Question 16: Why Not While feof

Explain why while (!feof(f)) { fgets(line, sizeof line, f); process(line); } is wrong, show the correct loop, and say how to find out afterwards why it ended.

Show answer

feof reports whether a previous read already reached the end of the file; it cannot predict. After the last good line the flag is still false, so the loop runs once more, fgets fails and leaves the buffer unchanged, and process handles stale data (the last line twice).

Drive the loop on the return value of the read: while (fgets(line, sizeof line, f) != NULL) { process(line); }.

Afterwards test ferror(f): if true, a real read error ended the loop (report it with perror); otherwise feof(f) is true and it was the normal end of input.

Multiple Choice · Week 27: Error Handling Strategies

Question 17: Assert Or Real Check

Which of these conditions belongs in a real runtime check that stays in the release build, not in an assert?

C: a missing file is a legitimate state of the world, not a bug, and assertions vanish under NDEBUG, so the release build would silently continue with a NULL stream. A, B and D are programmer errors or invariants that should be impossible if the code is correct; those are what assert documents.

Classic Question · Week 27: Error Handling Strategies

Question 18: The goto Cleanup Idiom

A function opens an input file, opens an output file, and allocates a buffer, and each step can fail. Describe the goto cleanup structure that releases exactly what was acquired on every path, and say why it is better than releasing in each early return.

Show answer

Declare every resource at the top, initialized to a null value (FILE *in = NULL, *out = NULL; char *buffer = NULL; bool ok = false;). Acquire each one in turn and on failure report and goto cleanup;. After the last step set ok = true; and fall into a single cleanup: block that releases everything: free(buffer); (safe on NULL), if (out != NULL) fclose(out);, if (in != NULL) fclose(in);, then return ok;. Check fclose on the written file, since the final flush can fail.

With a release in every early return, each new resource must be added to every branch, and the error paths are the least tested, so one branch eventually forgets a release. One exit makes correctness structural: adding a resource means one acquisition and one release.

Multiple Choice · Week 28: The Preprocessor and Modular Programming

Question 19: Variable Defined In Header

config.h contains int verbose = 0; with a correct include guard, and two .c files include it. What happens?

A: the guard only stops a second inclusion within one translation unit. Each .c file gets its own definition of an external name, so the linker finds two. The fix is extern int verbose; in the header and the single definition int verbose = 0; in one .c file. Static would give private copies, but this declaration is not static.

Output Question · Week 28: The Preprocessor and Modular Programming

Question 20: Macro Pitfalls

What does this program print?

#include <stdio.h>

#define SQUARE_BAD(x) x * x
#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define STR(x) #x

int main(void)
{
    int i = 5;
    int j = 3;
    int m;

    printf("%d %d\n", SQUARE_BAD(2 + 3), SQUARE(2 + 3));
    m = MAX(i++, j);
    printf("%d %d\n", m, i);
    printf("%s\n", STR(SQUARE(2 + 3)));
    return 0;
}
Show answer
11 25
6 7
SQUARE(2 + 3)

SQUARE_BAD(2 + 3) expands to 2 + 3 * 2 + 3, which is 11; the parenthesized version gives 25. MAX(i++, j) evaluates its first argument twice: the comparison sees 5 and increments i to 6, and the chosen branch yields 6 and increments i to 7. The # operator turns its argument into a string without expanding it.

1 / 1 Sercan KÜLCÜ. All rights reserved.