CS4411
Practicum in Operating Systems

Practice in "C"

Examples to accompany the 8/31 Lecture

The following problems complement the lecture introducing C. Answers will not be posted, but any TA should be able to help with answering these questions in office hours.

Here's a complete list of the source files used for the Introduction to C slides:

Type Declarations

For help with type declarations, use the clockwise/spiral rule. A quick example of this was given in lecture, although was not labelled as such.

For each of the following, determine the type of x. For instance, 1. could be answered as, "x is an int." 2. could be answered as, "x is a pointer to an int."

1.  int x;
2.  int* x;
3.  int* x[];
4.  int (*x)(char, double);
5.  const double x;
6.  const double* x;
7.  double const x;
8.  double* const x;
9.  void (*x(void(*f)(int, double), char))(void(*f)(int, double), char)

Don't worry about number nine too much. It's overkill. Make sure you understand the function_pointers.c example on the web site.

Pointer Manipulation

For help with pointer manipulation, consider this stack overflow page conveniently title "pointer arithmetic".

  1. What are the values of x and y after the completion of this program?

    int x = 10;
    int y = 5;
    
    int* ptr = NULL;
    
    ptr = &y;
    *ptr -= x;
    ptr = &x;
    *ptr -= y;
    
  2. What is the value of *(s + 5)?

    char s[] = "hello world";
    

String Manipulation

What is the bug in the following code? Does it still exist if you use strncpy instead of strncat? What's the difference?

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[])
{
    if (argc != 3) return -1;

    /* Two arrays */
    char a[16];
    char b[16];

    /* Clear both arrays */
    memset(a, 0, sizeof(a));
    memset(b, 0, sizeof(b));

    /* Concatenate the first command line arg to a (second to b) */
    strncat(a, argv[1], 16);
    strncat(b, argv[2], 16);

    printf("a : %s\n", a);
    printf("b : %s\n", b);

    return 0;
}

Memory Allocation

Write a program to generate the fibonacci sequence up to its 47th position (0-indexed). Do it using only the following local variables:

int* tmp;
int* prev;
int* cur;

Each number of the sequence should be allocated as a separated integer using malloc. Make sure not to double-free or leak memory.

Bonus challenge: Instead of immediately freeing memory, add unused memory to a pool of allocated objects, drawing from the pool as necessary. Try for as low an upper-bound on allocation as possible.

Memory Allocation Questions

These questions are designed to get you thinking about trade offs of various design decisions you can make using C. There are some right answers, and definitely some wrong ones.

  1. When passing a pointer into a function, is it the caller or the callee's job to free the memory?
  2. Who is responsible for the cleanup of pointers returned from a function? Consider where the pointers may have come from.
Powered by Firmant