C for the exam

On this page
  1. The course's checklist
  2. Program structure and input
  3. Pointers and memory
  4. Files
  5. Processes
  6. Signals
  7. Threads
  8. Synchronisation
  9. Dangerous calls

The C you need to read and write on the exam, based on the course's own checklist: program structure, input and arguments, pointers, files, processes, threads and synchronisation – with short templates for each.

The course's checklist

For the exam you need to be able to read, understand and write simple C programs. The course lists (not exhaustively):

  • Basic layout and syntax of a .c file
  • stdin, stdout, stderr
  • Reading user input from stdin and from command-line parameters
  • Control flow: while, for, if
  • Basic data types (int, char, void) and pointers to them, with * and &
  • Correct use of the libc-wrapped system calls from the lectures: fork(), execve(), wait(), open(), read(), write(), close(), printf()/snprintf()/fprintf(), signal(), malloc(), free(), mmap(), …
  • The structure of a simple shell
  • Correct use of pthread_* functions
  • Correct use of locks, semaphores and condition variables (pthread_mutex_t, sem_t, pthread_cond_t) without causing deadlocks
  • Security implications of C: stack layout, stack buffer overflows, dangerous calls like gets()

Pseudocode is usually accepted, but use the correct function names.

Program structure and input

#include <stdio.h>

int main()
{
    int number1;
    int number2;
    int sum;

    printf("Enter two integers: ");
    scanf("%d %d", &number1, &number2);   // & gives scanf the address to write to

    if(number1 > 100 || number2 > 100)
    {
        printf("At least one number is too large!\n");
        return 1;                           // non-zero exit status = error
    }
    sum = number1 + number2;
    printf("Sum of %d and %d is %d\n", number1, number2, sum);
    return 0;
}

Read a whole line safely with fgets(line, sizeof(line), stdin), never gets. fgets keeps the newline: strip it with line[strcspn(line, "\n")] = '\0';.

Command-line arguments

argc is the number of arguments including the program name; argv[0] is the program name and argv[1] the first real argument. Convert numbers with atoi (from <stdlib.h>; returns 0 on error).

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

// ./myprog 3 "String"  prints  StringStringString
int main(int argc, char *argv[])
{
    int N = atoi(argv[1]);
    for (int i=0; i<N; i++)
    {
        printf("%s", argv[2]);
    }
}

Pointers and memory

  • &x is the address of x; *p is the value p points to.
  • Local variables live on the stack: void func() { int a; }
  • Dynamic memory lives on the heap: void *mem = malloc(256); … free(mem);
  • Check malloc for NULL and free what you allocate.

Files

With the C library

#include <stdio.h>

int main()
{
    FILE *f = fopen("numbers.txt", "w");   // "r" to read; returns NULL on error
    for(int i=1; i<=30; i++)
    {
        fprintf(f, "%d\n", i);
    }
    fclose(f);
}

With system calls

#include <fcntl.h>
#include <unistd.h>

int fd = open("out.txt", O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR);
if (fd < 0) { perror("open"); return 1; }
write(fd, buf, len);     // returns bytes written, or -1
fsync(fd);               // force to disk
close(fd);
unlink("out.txt");       // delete

Print errors to stderr with perror("message") or fprintf(stderr, …).

Processes

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main()
{
    pid_t pid = fork();
    if (pid == 0) {                         // child
        char *args[] = { "ls", "-l", NULL };
        execvp(args[0], args);              // only returns on error
        perror(args[0]);
        exit(1);
    }
    wait(NULL);                             // parent: wait for the child
    printf("parent: child finished\n");
    return 0;
}

Remember: fork returns 0 in the child and the child's PID in the parent. Programs that call fork in a loop create more processes than you expect – draw the process tree. See the programming interface for the shell.

Signals

#include <signal.h>

void handler(int signum) { /* ... */ }

int main()
{
    signal(SIGWINCH, handler);
    while (1)
        pause();            // sleep until a signal arrives
}

Threads

#include <stdio.h>
#include <pthread.h>
#define NUMTHREADS 5
pthread_t threads[NUMTHREADS];

void *go(void *param)
{
    printf("Thread %ld says hello\n", (long)param);
    pthread_exit(param);                // or: return param;
}

int main()
{
    for (long i = 0; i < NUMTHREADS; i++)
        pthread_create(&threads[i], NULL, go, (void *)i);
    for (int i = 0; i < NUMTHREADS; i++) {
        void *retval;
        pthread_join(threads[i], &retval);
        printf("main: thread %d returned %ld\n", i, (long)retval);
    }
}

Compile with gcc -o prog prog.c -lpthread. The four arguments to pthread_create: where to store the thread handle, attributes (NULL), the function to run, and one void * argument.

Synchronisation

// Lock
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&lock);
/* critical section */
pthread_mutex_unlock(&lock);

// Condition variable: always wait in a loop, holding the lock
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_lock(&lock);
while (!ready)
    pthread_cond_wait(&cond, &lock);
pthread_mutex_unlock(&lock);

// Semaphore (#include <semaphore.h>)
sem_t s;
sem_init(&s, 0, 1);     // 0 = shared between threads, initial value 1
sem_wait(&s);
/* critical section */
sem_post(&s);
sem_destroy(&s);

To avoid deadlock, take multiple locks in the same order in every thread. See synchronisation and deadlock.

Dangerous calls

  • gets(buf) – no length limit; use fgets(buf, sizeof(buf), stdin).
  • Copying into a fixed-size buffer without checking the length is how the Morris worm got in. See buffer overflows.

On earlier exams

Practise this topic in the quiz (7 questions)