Sample Programs
The following sample programs (adapted from those provided by Jeff Ondich) will help you explore many useful features in C.
Study them! It is expected that you read them as the term progresses, just as you would the textbook or any other assigned reading.
Here are some things to keep in mind as you explore these programs:
-
Ask questions: You aren’t expected to understand everything the first time you read these sample programs. As you work through them, write down your questions and make sure to get them answered!
-
Experiment: The beauty of programming is that you can (usually) make changes and immediately see the impact when re-running your code. Play around with these samples to help you understand them! If you find yourself thinking I wonder what happens if I make this change…, just try it!
-
Build these programs: For most of these samples, you should use the following compilation approach:
gcc -Wall -Werror -g -o hello hello.c
We will talk about the different parts of this command throughout the first few days of the term.
- Pedagogical comments vs. production comments: These programs are written to have a lot of explanatory comments, because they are designed as pedagogical programs (to teach you things!), not as production programs. Production code (i.e., that intended for use by end users or even as homework submissions) should following the commenting advice in our style guide. You are welcome to borrow code from these samples, but delete these pedagogical comments before you are ready to submit.
Samples
Getting started in C, char
s and strings, arrays, pointers:
- hello.c -
printf
- args.c -
argc
,argv
- character_counter.c - command-line arguments, reading from a file
- charstar.c - various notation for pointers to
char
s - strings.c - null-terminated character strings
- arrays2d.c - 2-dimensional arrays (weird, but cool!)
- pointers.c - pointers
Bits and bytes, integers:
- sizes.c -
sizeof
, byte count for common types - memory.c -
*
,&
,.
,->
- bitwise.c - bitwise operations
~
,&
,|
, and>>
- integer_rep.c - exploration of integer byte ordering
- show_bytes.c - byte orderings for common types
- integers.c - store integer values in various ways
- printing_bytes.c -
printf
and its implicit casting toint
for%x
Program representation and ISA:
- program_memory.c - a program to assemble and explore
- gdb_test.c - a program to use with
gdb
- arrays.c - treating a block of memory as different types of arrays
- switch.c -
switch
statements in C
Buffer overflow attacks:
- attack.c - a program that is susceptible to buffer-overflow attacks
Process-related samples:
- Makefile - a simple Makefile for all process-related samples
- Getting started with processes:
- Redirection:
- Helpful for writing your shell:
- Pipes and signals: