CS010 Practice 4

C Memory Management

 

 

  1. Do Exercise 14 from Chapter 13 of King again. This time use pointers, malloc and free to allocate memory for your strings instead of using arrays with a static size. Compare these two versions. Which do you like better and why?
  2. Do exercise 5 from Chapter 17 of King.
  3. 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, " Williams beats Wesleyan");
       
      s2 = (char *) malloc (1);
      strcpy (s2, "Amherst");
       
      printf ("%s\n", s1);
      exit (0);
    }