Pointer Potions
- Starter Code: fork wellesleycs240 / cs240-pointers (just once!), keep the "cs240-pointers" name, and add bpw as admin. (Need help?)
- Submit:
- Commit and push your final revision and double-check that you submitted the up-to-date version. (Need help?)
- Do not submit a paper copy.
- Relevant Reference:
- Collaboration: Optional pair-programming or individual assignment policy, as defined by the syllabus.
A version of this page with a clearer command line definition has been posted.. This old version of the page is still accessible if you prefer it instead.
Contents
- Overview
- Starter Code
- Command Structure and Parsing
- Specification
- Memory Allocation Rules
- Coding Style Rules
- Submission and Grading
- Workflow
- Compile and Run
- Test and Debug
Overview
[Preparation: If you did not do the later Predictions sections or a few of the Practice Pointer Programming examples on the pointers lab, complete those before starting this assignment.]
The main task of this assignment is to implement a shell command parser as a small library in C. The shell is the program that reads and interprets the commands you type at a command line terminal. Later in the semester, you will build a full shell. For now, we focus on the first step toward a shell: splitting a user’s command line into its meaningful parts.
This parser takes a command line, stored as a single string, and converts it to an array of strings representing the command and its space-separated arguments. This may sound trivial given your previous programming experience with strings, but you will be using a substantially different and lower-level toolbox to accomplish the job. We prohibit the use of string manipulation functions from the C standard library to force you to confront how strings are implemented and manipulated in memory.
The goals of this assignment are:
- to become familiar with the byte-addressable memory model, C pointers, arrays, and the link between pointer arithmetic and array indexing;
- to practice principled techniques for reasoning about program execution, using assertions and structured debugging.
Please skim this document before starting work. Pay special attention to orange boxes like this one.
Programming with C pointers is like brewing a potion. Both tend to flare up in your face unless you brew them just right.
For each stage in the suggested workflow:
- Plan carefully before typing any code.
- Implement one step at a time (with useful assertions).
- Test each step extensively before implementing the next.
- Commit each tested step before implementing more.
This careful process will save time by catching bugs early and saving working versions you can recover if things start going wrong later.
Starter Code
Starter code for this assignment is a shared Mercurial repository. Get a copy of the code as follows (need help?):
- Fork wellesleycs240 / cs240-pointers once per team to create your own copy on Bitbucket.
- Add bpw and your partner as Admins on the repository.
- Clone your Bitbucket repository to your local computer account:
hg clone ssh://hg@bitbucket.org/yourusername/cs240-pointers
If you have chosen to work with a partner, do your programming together, sitting in front of one screen. If both partners will use a copy of the code, please read the Mercurial Team Workflow before trying that.
Your working copy should contain several files covering this week’s lab material and this assignment:
Makefile
: recipes to compile the various partscommand.c
: a file where you will implement a parser for simple shell commandscommand.h
: a C header file describing the functions you will implement incommand.c
command_test.c
: tests for your command parser
To compile the command-parsing code with the test harness, run make
command_test
. Run the compiled executable with ./command_test
.
Command Structure and Parsing
Your will write a handful of functions to convert command lines (strings) to command arrays (arrays of one-word strings) and work with command arrays. This section describes command lines, command arrays, and parsing in general. The next section describes the specific functions you will write.
Command Lines
UPDATE 11:30pm 26 October: this is an older command line definition that was accidentally published when this assignment was posted. We think it is less clear than the new definition, which is accessible here.
A command line is a string. Here are two examples:
"ls -l cs240-pointers"
"emacs cs240-pointers/command.c &"
The command-line string may be comprised of several words (contiguous non-space characters) that indicate substructure:
- The first word is the name of the command to run:
ls
oremacs
- All remaining words are arguments to pass to this command:
-l
andcs240-pointers
orcs240-pointers/command.c
. - An optional
&
character at the end is never an argument (or part of an argument). For the parser, it sufficies to report the presence or absence of&
and leave it out of the resulting command array.- Looking ahead a few weeks to the shell asignment, the
&
is metadata indicating that the command should be run as a background command. Command lines not ending with&
indicate foreground commands. When executing a foreground command, the shell waits for the command to finish before giving the next command prompt. When executing a background command, the shell gives the next prompt immediately, while the command continues to run in the background. Implementing command behavior will be part of our later shell implementation.
- Looking ahead a few weeks to the shell asignment, the
Valid Command Lines
All command lines without the &
character are valid. If the &
character appears in a command line, it is allowed to appear only as the last non-space character of the command line. For example, these are valid command lines:
"emacs &"
"emacs& "
" sleep 10 & "
These are invalid command lines (for this assignment – some are valid in other shells):
"&uhoh"
" & uh oh"
"uh & oh"
"uh& &oh"
"uh oh & &"
Command Arrays
The parser converts a command line into a command array, an array of strings representing the words of the command line, in order, terminated by a NULL
element. Recall that a string in C is not a special type; it is just an array of char
s terminated by a null character ('\0'
). A command array is thus an array of pointers to arrays of char
s and has the type char**
. All arrays in this structure must be null-terminated, using the right “null” for each array.
'\0'
is the null character. As a character (char
), it is one byte in size.
NULL
is the null address. As an address (pointer value), it is one machine word in size.
Do not mix them up!
Literal character (char
) values in C are given in single quotes: 'a'
.
Literal string values are given in double quotes: "a"
.
Do not mix them up!
Comparing 'a' == "a"
will yield false
. 'a'
is the one-byte ASCII encoding of a
, a value of type char
. "a"
is the address of the start of the one-character null-terminated string "a"
in memory, a one-word value of type char*
.
Here is an example command array for the command line string "ls -l cs240pointers"
:
Command Array: Null-Terminated Strings
Index Contents (stored elsewhere in memory)
+----------+
0 | ptr *----------> "ls"
+----------+
1 | ptr *----------> "-l"
+----------+
2 | ptr *----------> "cs240-pointers"
+----------+
3 | NULL |
+----------+
Here is the same array drawn another way and showing how the array is arranged in memory, with each element’s offset from the base address of the array. Addresses grow left to right, and are assumed to be 64 bits (8 bytes), so indices are related to offsets by a factor of 8.
Index: 0 1 2 3
Offset: +0 +8 +16 +24 +32
+-------+-------+-------+-------+
Contents: | * | * | * | NULL |
+---|---+---|---+---|---+-------+
| | |
V V V
"ls" "-l" "cs240-pointers"
Although we draw “strings” in the above pictures, this is an abstraction. Each string is actually represented by a '\0'
-terminated array of 1-byte characters in memory. Since each element is one byte, the addresses of adjacent characters differ by 1 and the offset is identical to the index.
Index: 0 1 2
Offset: +0 +1 +2 +3
+-----+-----+-----+
| 'l' | 's' |'\0' |
+-----+-----+-----+
Note: Practice reading memory diagrams every which way. Pay attention to what direction addresses grow. We are intentionally using different conventions in different drawings to help you get used to thinking on your feet…
Specification
You must write four functions (plus any necessary helper functions) supporting command parsing in command.c
according to the headers in command.h
. If you write helper functions, be sure to read about how C function declarations work. We give a plan for implementation and testing below.
-
char** command_parse(char* line, int* foreground)
Parse a command-line string
line
and:- If the command line is valid:
- Store
0
where theforeground
pointer points if the command line contains&
after the last word. Store1
if it contains no&
. - Return a command array corresponding to the command-line string.
- Store
- If the command line contains invalid use of
&
, returnNULL
without setting foreground/background status.
- If the command line is valid:
-
void command_print(char** command)
Print a command array in the form of a command line, with the command words separated by spaces. Do not include a newline at the end. (We will rely on that when reusing this code later.) You will want to learn how to use printf.
-
void command_show(char** command)
Print the structure of a command array to aid in debugging and data inspection.
The output should make it clear exactly what strings the command array holds, but the format is left to you. For example, given the command line:
"ls -l cs240-pointers "
the output of a
command_show
implementation using helpful formatting will distinguish a correct command array where all spaces are stripped away:command array: - "ls" - "-l" - "cs240-pointers" end
from an incorrect command array that contains some trailing spaces in words:
command array: - "ls " - "-l " - "cs240-pointers " end
Calling
command_print
, which does not delineate the bounds of words explicitly, may not make this so clear:ls -l cs240-pointers
-
void command_free(char** command)
Free all parts of a command array structure previously created by
command_parse
and not previously freed.
Memory Allocation Rules
Follow these memory allocation rules in your code:
- Clients of the command library own and manage the memory
representing command line strings.
- Command library functions must never free nor mutate command line strings.
- Clients may free or mutate command lines at any time outside a call to command library functions.
- The
command_parse
function must allocate command array structures dynamically withmalloc
and return them to the caller. Once returned, these structures are own by the caller.- Clients will not mutate command array structures.
- Clients may call
command_free
to free a command array at any time.
- The command library functions must not allocate any memory that they do not return as part of a command array structure.
- Assuming that the client code eventually calls
command_free
on every command array returned by calls tocommand_parse
, all allocated memory is eventually freed.
Coding Style Rules
Follow this general C style guide as a baseline, along with the following specific rules:
- Do not use array notation. Use idiomatic pointer style instead. See below.
- Document in comments how your code implements the specifications
provided, connecting your C implementation to the specification.
- Our sample solution for
command_parse
is under 70 clean lines of code and 20–30 lines of comments.
- Our sample solution for
- Document pre- and post-conditions and use assertions to check assumptions where reasonable.
- Use well-scoped helper functions where reasonable.
- Clean solutions are possible with and without helper functions.
- If using helper functions, match them to well-defined sub-problems with clear arguments and results.
- Be sure to order function headers properly.
- Prefer simple efficient code over complicated code.
- Our sample solution for
command_parse
is under 70 clean lines of code and 20–30 lines of comments.
- Our sample solution for
- Ensure your code is free of compiler warnings (and, obviously, errors).
- Ensure your code is free of run-time errors, including memory errors
and leaks as detected by
valgrind
.
Idiomatic Pointer Style
For full credit, your submitted code must use only pointers and pointer arithmetic, with no array notation. Choosing pointer arithmetic over array indexing is not necessarily the best choice for clear code in all cases – here we require you to use pointers to learn how arrays and array operations are represented under the hood.
A simple way to think with arrays but write with pointers is to use
*(a + i)
wherever you think a[i]
. However, this simple
transformation rarely matches an idiomatic pointer style.
An idiomatic loop over an array with array indexing typically uses an integer index variable incremented on each iteration. Keep the scope of the index variable (or “loop variable”) as small as possible for the task.
// pre: a is the address of a null-terminated string.
// post: replaces all characters in a by 'Z'
for (int i = 0; a[i] != '\0'; i++) {
a[i] = 'Z';
}
An idiomatic loop over an array with pointer arithmetic typically uses a cursor pointer that is incremented to point to the next element on each iteration. Keep the scope of the cursor pointer variable as small as possible for the task.
// pre: a is the address of a null-terminated string.
// post: replaces all characters in a by 'Z'
for (char* p = a; *p != '\0'; p++) {
*p = 'Z';
}
Your final code should contain zero array[index]
operations.
Submission and Grading
Before submitting, disable any printing in command.c
functions other than
command_print
and command_show
.
Submit your work by committing and pushing your latest work to your Bitbucket repository.
Your grade is derived as follows:
- 60 points: Functionally correct implementation of the specification
- When called on well-structured inputs, your code must return
correct results with no run-time memory errors
(as detected by
valgrind
) or crashes.
- When called on well-structured inputs, your code must return
correct results with no run-time memory errors
(as detected by
- 10 points: Correct and efficient memory management
- Your code allocates no more memory than strictly necessary.
- Your code does not suffer memory leaks (as detected by
valgrind
).
- 30 points: Design, style, and documentation
We compute the correctness and efficiency components of your grade using a private suite of test inputs. You should develop your own large suite of test inputs to help check that your code meets the specification. We will not grade your tests themselves, but preparing and using them will help you ensure your code is fully correct and efficient.
Workflow
Follow the workflow below, much of which also corresponds closely to
the functionality of command_parse
as described in command.c
.
-
Finish the Predictions and Practice Programming sections of the pointers lab, before starting to build your command parser.
-
Add several more hard-coded command array test cases to
command_test.c
. -
Implement
command_show
andcommand_print
first. They are only a few lines of code each. Test them on the constant, statically allocated command arrays incommand_test.c
. -
Add several more hard-coded valid and invalid command lines to
command_test.c
to test many aspects of the specification. -
Implement
command_parse
in stages, testing each stage on several inputs and committing a working version before continuing.-
Count the number of words in
line
and detect use of&
, returningNULL
for invalid commands and marking the foreground/background status for valid commands. -
Allocate the top-level command array.
-
Copy each word in
line
into a newly allocated string and save it in the command array.
-
-
Implement and test
command_free
.
Compile and Run
To compile the command-parsing code with the test harness, run make
command_test
(or just make
). Run the compiled executable with ./command_test
.
Test and Debug
Programming with pointers in C is error-prone, even for experts. Haphazard print-based testing is an inefficient (and often ineffective) use of your time. Wield the tools in this section to catch errors sooner and faster.
Assert the truth.
Assertions are “executable documentation” or “executable specifications”: they document rules about how code should be used or how data should be structured, but they also make it easier to detect violations of these rules (a.k.a. bugs!). Use the assert(...)
tool in C by including assert.h
and asserting expected properties. For example, the provided code already includes code that asserts that the arguments to command_
functions are not NULL
. Thus if a NULL
argument is ever passed to these functions, an error message will be printed and execution will halt immediately. Detecting errors early like this (vs. crashing or corrupting data later wherever the code depends on this assumption) saves a lot of time. Add assertions to make the “rules” of your code clear wherever you make assumptions.
Write extensive tests.
Develop your own large suite of test inputs to help check that your
code meets the specification. We will not grade your tests
themselves, but preparing and using them will help you ensure your
code is fully correct and efficient. We have provided a test harness
in command_test.c
where you can easily add new tests.
- Add more command line strings to the
COMMAND_LINES
array incommand_test.c
and updatingNUM_COMMAND_LINES
to match. - For early testing of
command_print
andcommand_show
before implementingcommand_parse
, add command arrays toCOMMAND_ARRAYS
.
Use Valgrind.
Valgrind is an extended memory error checker. It helps catch pointer errors, misuse of malloc
and free
, and more. Run valgrind on your compiled program like this: valgrind ./command_test
. Valgrind will run your program and watch it execute to detect errors at run time. See the tools page for additional reference links.
Use GDB.
Use GDB to help debug your programs. (Review previous lab activities for tips.) When debugging programs with pointers, pay special attention to the pointer values your program generates. Inspect them like other variables or use the address-of (&
) and dereference (*
) operators at the gdb
prompt to help explore program state. See the tools page for additional reference links.
Does GDB tell you that it cannot display something due to compiler optimizations? If so, turn off compiler optimizations by adding -O0
(that’s “space dash Capital-Oh zero”) at the end of the CFLAGS = ...
line in your Makefile
. This will take effect the next time you use make
to compile your code. The CFLAGS
variable here determines what flags are passed to the compiler. -O0
enables level zero of optimization (i.e., none).
Emacs Tips
- Compile from within Emacs by typing
M-x compile
, editing themake
command that appears in the mini-buffer (justmake
should work), and hit enter. The compiler output will appear in an Emacs buffer where you can click on errors to jump to the source line involved. Note: the mini-buffers where you type in commands have history accessible with up and down arrows. - Run GDB from with Emacs with
M-x gdb
, starting from a C buffer.- Click left margin to set/delete breakpoints.
- Use buttons at top to run, continue, step, next, navigate up and down the stack, etc.
C Function Declarations
In C, a function is allowed to be used only after (i.e., later in the file than) its declaration. This differs from Java, which allows you to refer to later methods. When declaring helper functions, you can do one of a few things to deal with this:
- Just declare your helper function before the functions that use it.
-
Write a function header earlier in the file and the actual definition later in the file. The function header just describes the name and type of the function, much like an interface method in Java. For example:
// A function header declares that such a function exists, // and will be implemented elsewhere. int helper(int x, int y); // Parameter names are optional in headers. int helper2(char*); void needsHelp() { // OK, because header precedes this point in file. helper(7, 8); helper2("hello"); } int helper(int x, int y) { return x + y; } int helper2(char* str) { return 7; }
-
If the functions would likely get used elsewhere, then put the header in a header file, a file ending in
.h
that contains only function headers (for related functions) and data type declarations. For example, if you added another general function (not just a helper function) for manipulating commands (not required in this assignment), it would be best to place a function header for it with the other function headers incommand.h
so that users of your command library can call it.Header files are included (essentially programmatically copy-pasted) by the
#include
directive you often see at the tops of C source files. Then these functions can be used and their implementations will later be found elsewhere if compiled correctly.