Skip to main content

C Compilation and Mental Model Lab

This practice page exercises Cluster 1 (The C Mental Model). Finish the concept pages first.

Retrieval Prompts

  1. State the four stages of C translation and the artifact each produces.
  2. State one example each of implementation-defined, unspecified, and undefined behavior in C.
  3. State what a "translation unit" is.
  4. State what the -E, -S, and -c flags do for gcc.
  5. Name three things that changed between C89 and C99.

Compare and Distinguish

Separate these pairs clearly:

  • the abstract machine that the C standard defines vs. the hardware machine that runs the binary
  • a declaration vs. a definition
  • a compiler error vs. a linker error
  • implementation-defined behavior vs. unspecified behavior vs. undefined behavior
  • #include "foo.h" vs. #include <foo.h>

Common Mistake Check

For each statement, identify the error:

  1. "The preprocessor imports headers like Python imports modules."
  2. "If the program runs fine in debug mode, there is no undefined behavior."
  3. "The compiler reports every undefined reference it detects."
  4. "gcc -std=c89 means the compiler targets only 32-bit processors."
  5. "A translation unit is the same thing as an executable."

Mini Application

Do all tasks in one terminal session.

Write hello.c with a #define, a #include, and a printf.

  1. Run gcc -E hello.c -o hello.i and inspect the result. Count lines and name two things that ended up there.
  2. Run gcc -S hello.c -o hello.s and look at the top of the file. Identify the main symbol.
  3. Run gcc -c hello.c -o hello.o. Run nm hello.o. Classify each symbol as defined (T), undefined (U), local (t), etc.
  4. Run gcc hello.o -o hello. Run ./hello. Confirm the output.
  5. Now create bad.c that calls unknown_fn() without defining it. Which command fails, and what does the error message start with?

Build the full gcc -Wall -Wextra -std=c11 hello.c -o hello and record any warnings.

Undefined Behavior Reading

Classify each program as defined, implementation-defined, unspecified, or undefined. Justify in one sentence.

  1. unsigned int u = 0; u--;
  2. int i = INT_MAX; i++;
  3. int i = 0; int *p = &i; *(p + 1) = 5;
  4. char c = 200; on a platform where char is signed
  5. int a[3]; printf("%d", a[3]);
  6. int i = 0; int x = i + i++;
  7. int n = 3; printf("%ld", n);
  8. void *p = NULL; *(int *)p = 7;

C Standards Reading

Given a 10-line snippet, identify the oldest standard it conforms to. Tag anything that would fail on -std=c89:

// sum in range
int sum_range(int lo, int hi) {
int s = 0;
for (int i = lo; i <= hi; i++) {
s += i;
}
return s;
}

Which features here require C99 or later?

Evidence Check

This page is complete only if you can:

  • run the pipeline end-to-end and explain each stage's output in sentences
  • produce a repeatable classification of at least 10 UB reading snippets
  • identify the C standard an unfamiliar snippet targets