Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Fixing unsafe C calls

After this lesson: I can replace an unsafe C call with a bounded one and prove the fix with a sanitizer.

60 min lesson7 commandsCompilers and computer architecture lab: gcc, flex, bison and RISC-V in one VM

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

A badge for a very long name

A college prints visitor badges such as "Ann in B12". It works for every name in testing.

Then a visitor called Christopher-Robin arrives for Lecture Theatre Two. Three lines of the program were never safe; they were only lucky.

By the end of this lesson

Note

I can replace an unsafe C call with a bounded one and prove the fix with a sanitizer.

Key words

WordWhat it meansExample
Unbounded copya copy that never checks the space it writes tostrcpy
Bounded calla call that is told the size of its targetsnprintf
Truncationcutting text short to fit
Format stringthe first argument of printf, which says how to print
Length checkrefusing input that will not fit

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Three unsafe calls in one function

strcpy copies the name with no idea how big label is. sprintf writes the line with no idea how big line is. printf(line) treats text the user typed as instructions for printing.

Write the program and build it with warnings on.

Write badge.c and build it

Command
mkdir -p ~/mem/fix && cd ~/mem/fix && cat > badge.c <<'END'
#include <stdio.h>
#include <string.h>
void badge(const char *name, const char *room) {
  char label[12];
  char line[24];
  strcpy(label, name);
  sprintf(line, "%s in %s", label, room);
  printf(line);
  printf("\n");
}
int main(int argc, char **argv) {
  if (argc < 3) return 1;
  badge(argv[1], argv[2]);
  return 0;
}
END
gcc -Wall -O2 -o badge badge.c && ./badge Ann B12

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

A long name under AddressSanitizer

Command
cd ~/mem/fix && gcc -g -fsanitize=address,undefined -fno-omit-frame-pointer -Wno-format-security -o badge-asan badge.c && DEBUGINFOD_URLS= ./badge-asan Christopher-Robin B12 2>&1 | grep -E 'ERROR|of size|SUMMARY'

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

A long room under AddressSanitizer

Command
cd ~/mem/fix && DEBUGINFOD_URLS= ./badge-asan Ann Lecture-Theatre-Two 2>&1 | grep -E 'ERROR|of size|SUMMARY'

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Text is data, never a format

A % in a name would make printf(line) look for arguments that were never passed. That prints the wrong thing or crashes.

The fix is always the same: printf("%s\n", line). Keep -Wformat-security on so the compiler flags every case.

gets cannot be used safely at all

gets reads a line into a buffer it was never told the size of. No caller can make it safe, so C removed it in 2011.

Today's gcc will not even build a program that uses it. Try it.

Try to build a program that uses gets

Command
mkdir -p ~/mem/fix && cd ~/mem/fix && cat > ask.c <<'END'
#include <stdio.h>
int main(void) {
  char name[16];
  gets(name);
  printf("hello %s\n", name);
  return 0;
}
END
gcc -o ask ask.c 2>&1 | grep -E 'error'

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

A common mistake

Warning

Many people think strncpy is the safe strcpy. When the source is too long it copies no ending zero, so the next read runs past the buffer. Check the length first, or use snprintf, which always ends the text.

Worked example: each unsafe call and its replacement

UnsafeWhyUse instead
gets(buf)Never knows the sizefgets(buf, sizeof buf, stdin)
strcpy(dst, src)Never checks the spacea length check, then snprintf(dst, sizeof dst, "%s", src)
sprintf(dst, ...)Never checks the spacesnprintf(dst, sizeof dst, ...) and check what it returns
printf(text)Text read as a formatprintf("%s", text) or puts(text)
strcat(dst, src)Never checks the spacetrack the length used, then snprintf

The cells students fill in are left blank in this preview.

Check, bound, then print

badge now refuses a name that will not fit, copies with snprintf, and checks that snprintf did not have to cut the line short. It prints with "%s".

It returns -1 so main can say "refused: too long" instead of printing half a badge.

Rewrite badge.c and build it

Command
cd ~/mem/fix && cat > badge.c <<'END'
#include <stdio.h>
#include <string.h>
int badge(const char *name, const char *room) {
  char label[12];
  char line[24];
  if (strlen(name) >= sizeof label) return -1;
  snprintf(label, sizeof label, "%s", name);
  int n = snprintf(line, sizeof line, "%s in %s", label, room);
  if (n < 0 || (size_t)n >= sizeof line) return -1;
  printf("%s\n", line);
  return 0;
}
int main(int argc, char **argv) {
  if (argc < 3) return 1;
  if (badge(argv[1], argv[2]) < 0) puts("refused: too long");
  return 0;
}
END
gcc -Wall -Wextra -Wformat-security -O2 -o badge badge.c && ./badge Ann B12

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Prove it with the same three inputs

Command
cd ~/mem/fix && gcc -g -fsanitize=address,undefined -fno-omit-frame-pointer -o badge-asan badge.c && for who in "Ann B12" "Christopher-Robin B12" "Ann Lecture-Theatre-Two"; do DEBUGINFOD_URLS= ./badge-asan $who; done

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Replace gets with fgets

Command
cd ~/mem/fix && cat > ask.c <<'END'
#include <stdio.h>
#include <string.h>
int main(void) {
  char name[16];
  if (fgets(name, sizeof name, stdin) == NULL) return 1;
  name[strcspn(name, "\n")] = 0;
  printf("hello %s\n", name);
  return 0;
}
END
gcc -Wall -g -fsanitize=address -o ask ask.c && echo Bartholomew-Fitzwilliam | DEBUGINFOD_URLS= ./ask

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Assignment: flag unsafe calls

A reviewer wants a quick list of risky calls in a C file. Write two functions.

findings(source) returns a list of (line_number, call) pairs, counting lines from 1, in order. Flag gets(, strcpy(, strcat( and sprintf( wherever they appear (but not fgets(, snprintf( or strncpy(). Also flag printf when the text after printf( does not start with a double quote: report it as "printf".

fix_for(call) returns the replacement from the lesson's table: "fgets", "snprintf" for strcpy, strcat and sprintf, and "printf(\"%s\", ...)" for printf.

Code: python
def findings(source):
    return []


def fix_for(call):
    return ""

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.