In Class Week9: Tuesday and Thursday

  1. Copy the files for today's class into your week9 directory, then change into that directory and check the contents:
         % cd ~/cs21/
         % mkdir week9
         % cd  week9
         % cp ~newhall/public/cs21/week9/*  .
         % ls

  2. Open up the printaddr.c and add the arguments to the printf statements to printout the specified value. Compile and run your program. What does this tell you about where different variables are located in memory?

  3. Open up dynarray.c and implement the CreateAndInitArray function, and test that it works.

    You will implement a function that returns a dynamically allocated array of int values initialized with values entered by the user. The function will read in a value for the number of ints to be read in (the size of the array), dynamically allocate an array of that size, and then fill it with values entered by the user. The function will return the dynamically allocated array, and will "return" the size of the array using pass-by-reference.

  4. Open up baddyna.c and take a look at the code to get an idea of the types of memory access errors in contains. Now compile it and try running it with valgrind and gdb to find where the segmentation fault is occuring (see the comment at the top of the file for information on how to run valgrind and gdb to find the error). Comment out the line that is causing the segmentation fault, re-compile, and re-run with valgrind and see what errors remain:
    	% valgrind ./a.out
    	# or to get more information about memory leaks:
            %  valgrind --leak-check=yes --show-reachable=yes ./a.out
    You also can give valgrind a command line option to write its output to a file that you can view using emacs or vi:
    	%  valgrind --log-file=memerrors ./a.out

    Valgrind is a useful tool for debugging memory access errors like stepping beyond the bounds of an array, memory leaks, and so on. Unfortuanetly it only works for checking dynamically allocated memory, so we have not used it up until now. Memory access errors are often the most difficult ones to find, so valgrind can save you many hours of frustrating debugging time by pointing you directly to the error.

    Some more information on using valgrind is available here.

  5. Open up arrayptrs.c and implement code to printout the contents of the array using pointer arithmetic to iterate through and access each array bucket.