CS010 Practice 6

Memory Management

Programming Exercises

  1. What does the following code do. Reason it through and then execute it and see what happens. Do you understand what happens?
    #include <stdio.h>
    #include <stdlib.h>
    int main () {
      char *s1;
      char *s2;
      s1 = (char *) malloc (1);
      strcpy (s1, "Kangaroo Wallaroo Wallaby");
      s2 = (char *) malloc (1);
      strcpy (s2, "Platypus");
      printf ("%s\n", s1);
      return 0;
  2. Write a readline function with the following signature:
    char *readLine ();

    When called, it should read in the next line of input from the keyboard. It should return the line, with the <CR> removed. Unlike gets, fgets, and the version of readline in the lecture notes, this version does not take any parameters. As a result, this version must allocate the memory to hold the input. You should do this in a way that wastes no memory. The returned address should point to a chunk exactly the size of what is needed to hold the returned string (including the terminating nul character). Any extra memory that is allocated during execution of the readline function should be freed before the function returns.

  3. Use the Unix commands covered in class today and previously to do the following tasks:
    • The file /usr/share/dict/words is a list of most English words. Count the number of words stored in the file.
    • How many words in this file contain "cow"?
    • How many unique three letter prefixes start at the beginning of words in this file? Compute this in several steps: (1) extract the first three letters of every line, (2) sort them, (3) remove duplicates, and (4) count them.
    • How many unique three letter prefixes start at the beginning of words in containing cow?
    • Use diff file1.txt file2.txt to compare two similar files in your directory. Look at the output of diff and understand what it is showing. Change on of the files and see how the output of diff changes.

Return to CS 010 Home Page