To read our expectations for code in this course, read C Standards
Open your WebTop in Entainer.
Run cs1010, select Download CS1010 content, then choose Volumes and Volume 6.
Work in the downloaded Volume 6 directory.
For each exercise, write your answer in student.c inside the named directory.
You may add helper functions there as well.
We handle reading input, preparing the arrays and strings, and printing the results,
so you do not need to change main.c or the header files.
None of these exercises requires you to allocate or free memory (e.g., with malloc) so do not do that.
The Makefiles enable ASan and UBSan.
Consider revisiting Tutorial 5: Sanitisers if you need help understanding a sanitiser report.
0. String Internals
Focus
Following pointers through null-terminated strings, writing into a destination, and returning pointers into existing strings.
Introduction
The C Standard Library provides a collection of functions for working with strings.
For example, the lecture introduces functions such as strlen and strcpy from the string.h library.
In this exercise, you will write your own simplified versions of some of these functions.
Doing so will help you understand exactly how they work “under the hood,“
and give you practice with low-level memory and pointer operations.
Your Task
Open the file 0-string-internals/student.c.
You will find the following function declarations:
Your task is to implement each of these functions.
Their behavior should closely mimic their standard library equivalents, with the simplified conversion rules for my_atoi described below.
You could use e.g., man 3 strstr to get info about a specific function.
In our code, the corresponding functions are prefixed with my_.
E.g. my_strstr in our code corresponds to strstr of the standard library.
All input strings are valid, null-terminated strings, and they may be empty.
Do not change a string passed through a char const * parameter.
For my_strcpy and my_strcat, we give you a writable destination with enough space for the result and its terminating null byte.
The source and destination do not overlap.
You do not need to allocate memory or print anything.
Note
You don’t have to implement them in this order.
Some functions are easier to implement than others.
Warning
You must not use any of the library functions from <string.h> (e.g., strlen, strcpy, etc.) in your implementations otherwise that defeats the purpose.
We’re here to prove to ourselves that we can write code that belongs in the C standard library as well. :)
Do not use other library string, memory-copy, or string-to-number functions to do the work either.
You may reuse functions you have implemented and add your own helpers in student.c.
my_strlen: Find the Length
Return the number of bytes (char elements) in src, not counting the null terminator.
A character encoded using multiple bytes contributes one to the length for each byte.
For example, "hello" has length 5, while the empty string "" has length 0.
my_strcpy: Copy a String
Copy string src into dst, including the null terminator.
Return the original dst pointer, which points to the beginning of the copied string.
The return value must not point to the terminating null byte.
For example, copying "cat" writes 'c', 'a', 't', and '\0' into four consecutive positions in dst.
Copying an empty string still writes one byte: the terminator.
my_strcat: Join Two Strings
Append string src to the end of string dst.
There should only be one null terminator at the end of the combined string.
The first character copied from src replaces the old terminating null byte in dst.
Write a new terminator at the end of the combined string,
and return the original dst pointer.
For example, if dst initially contains "Hello, " and src contains "world!",
then dst should contain "Hello, world!" afterwards.
The space in this example is part of the original destination;
your function does not add spaces of its own.
my_strchr: Find a Character
Return a pointer to the first occurrence of character c in string s, or NULL if not found.
The argument c represents a byte value that fits in unsigned char.
The terminating null byte counts as part of the string for this search.
If c is '\0', return a pointer to the terminator, including when s is empty.
For example, searching for 'a' in "banana" returns a pointer to the character at index 1.
Return a pointer into s, not a pointer to a copy of the character.
my_strcmp: Compare Two Strings
Compare two strings lexicographically.
Return 0 if equal, negative if s1 < s2, positive if s1 > s2.
A lexicographic comparison is similar to dictionary order:
compare the first character of each string;
if they differ, the string with the lower unsigned byte value is considered ‘less’.
If they are the same, compare the second character, and so on.
If one string is a prefix of the other, the shorter string is ‘less’.
Otherwise if the strings are identical, they are equal.
Only the sign matters; you do not have to return exactly -1 or 1.
For example, "cat" comes before "catalogue",
while "dog" comes after "cat".
Comparison is case-sensitive and uses byte values, rather than a language’s dictionary rules.
my_strstr: Find a Substring
A substring is a consecutive sequence of characters within another string.
Return a pointer to the location of the first occurrence of the string needle inside the string haystack, or NULL if not found.
The returned pointer must point into haystack.
For example, "ana" occurs twice in "banana".
Return a pointer to index 1, where the first occurrence begins.
An empty needle matches at the beginning, so return haystack, even if haystack is also empty.
my_atoi: Convert a String to an Integer
Convert the string src to an integer (similar to atoi).
For this exercise, use the following simplified rules.
Start at the first character, allow one optional leading '-',
then convert consecutive decimal digits until you reach a non-digit or the end of the string.
If there are no digits to convert, return 0.
For example, "-120cats" becomes -120 and "007" becomes 7.
Do not skip leading whitespace or accept a leading '+': " 12", "+12", "cats", and "-" all produce 0 under this exercise’s rules.
The mathematical value of the converted digits, after applying the sign, is guaranteed to fit in an int.
This includes the most negative int value.
Think carefully about intermediate calculations;
a final answer that fits does not guarantee that every intermediate value fits too.
Running and Testing
To compile: run make in 0-string-internals
To run: run ./string
To test: run make test
To invoke one of your functions:
Run the program using ./string
On the first line of input, type the name of the function you wish to run (for example, strcmp)
On each subsequent line, provide the arguments required by that function, one argument per line
For example, to compare two strings using strcmp, you would run:
./stringstrcmpabcabe
Here, the program is told to run your my_strcmp implementation on the strings "abc" and "abe".
The same convention applies to all the other functions.
Make sure to provide the correct number of arguments for each one.
Function
Expected Input Lines (after Function Name)
strlen
1 string
strcmp
2 strings
strcpy
1 string (source only, destination will be allocated for you)
strcat
2 strings (destination, source)
strchr
1 string, then 1 character; an empty character line means '\0'
strstr
2 strings (haystack, needle)
atoi
1 string (representing an integer)
Make sure you provide inputs in the correct order for each function.
Spaces in a string line are part of the string, and a blank line represents an empty string.
We handle the destination buffers for copying and concatenation.
To test one function at a time, use its C function name:
make test FUNCTION=my_strstr
All seven functions must compile even when you select only one function’s tests.
Examples
Example 1 (my_strlen)
strlen counts the punctuation and space too:
Input
strlenHello, CS1010!
Output
resulting string [Hello, CS1010!] has length 14
Example 2 (my_strcpy)
Copying writes the source string and its null terminator into the destination.
The returned pointer still points to index 0 of the destination:
Input
strcpycat
Output
pointer to destination returned as index 0copying [cat] into resulting string [cat]
Example 3 (my_strcat)
For concatenation, the second string is appended directly to the first.
The returned pointer still points to index 0 of the destination:
Input
strcatcatfish
Output
pointer to destination returned as index 0resulting string [catfish]
Example 4 (my_strchr)
Searching for a character finds its first occurrence.
The first a in banana is at index 1:
Input
strchrbananaa
Output
Char 'a' (ascii value 97) found in index 1 of [banana]
Example 5 (my_strcmp)
When one string is a prefix of the other, the shorter string comes first.
The program prints the comparison using the sign of the returned value:
Input
strcmpcatcatalogue
Output
[cat] < [catalogue]
Example 6 (my_strstr)
For a substring search, the program shows the first matching index,
then displays text starting there and marks the matched substring with dashes:
Input
strstrbananaana
Output
Found match starting from position/index: 1anana---
Example 7 (my_atoi)
Conversion stops when the first non-digit is reached:
Input
atoi-120cats
Output
resulting string [-120cats] was converted to integer -120
Hints
Hint
Which operations need to look at the terminating null byte itself?
If you advance a pointer while copying or concatenating,
how will you remember the original destination address to return?
For my_strstr, a helper that checks whether one string matches the start of another may be useful.
1. Extreme Distance
Focus
Finding elements through pointers, returning two addresses, and subtracting pointers within an array.
Introduction
You’ve already written functions that find the largest value.
This time, we want to know where both the smallest and largest values are stored,
and how far apart they are in the array.
For example, in [12, 3, 8, -2, 7], the smallest value is at index 3
and the largest is at index 0.
Their distance is 3 array positions.
We also want pointers to those two elements, so the caller can access them directly.
Your Task
In 1-extreme-distance/student.c, implement:
size_t extreme_distance(int *array, size_t size, int **smallest, int **largest);
The array contains size integers, with at least one element.
Find its smallest and largest values.
Store a pointer to the smallest element in *smallest
and a pointer to the largest element in *largest.
The caller passes the addresses of two separate pointer variables for these results.
If a value occurs more than once, choose its first occurrence.
Do not change the array.
Both output pointers must point to elements of the original array.
You do not need to allocate memory or print anything.
Return the absolute difference between the two elements’ positions.
Use pointer subtraction to calculate this distance.
Count array positions, rather than bytes: adjacent elements have distance 1.
The distance is always nonnegative, whichever extreme comes first.
If all elements are equal, both pointers point to the first element and the distance is 0.
This also applies to an array with just one element.
Negative values and zero are possible too.
Running and Testing
To compile: run make in 1-extreme-distance
To run: run ./extreme-distance
To test: run make test
On the first line, type the array size, from 1 to 100.
On the second line, type that many integers separated by spaces.
The program prints each selected element’s zero-based index and value,
followed by the distance returned by your function.
Examples
The largest element comes before the smallest:
Example 1
Input
512 3 8 -2 7
Output
Smallest: 3 (-2)Largest: 0 (12)Distance: 3
Choose the first occurrence of each extreme:
Example 2
Input
5-4 9 -4 2 9
Output
Smallest: 0 (-4)Largest: 1 (9)Distance: 1
Hints
Hint
Keep a pointer to each best candidate as you walk through the array.
How can you update the caller’s two pointer variables?
Which pointer should you subtract from which to get a nonnegative distance?
2. String to Integer
Focus
Converting a string to a number and returning a second result through a pointer-to-pointer.
Introduction
Let’s try a question that shows a natural use-case for pointers, string to integer conversion.
In 2-strtoi/student.c, implement:
int strtoi(char const *str, char **endptr);
Your Task
General Behaviour:strtoi converts the initial part of a null-terminated string to a decimal integer.
Skip leading whitespace (as determined by isspace) and accept one optional + or - sign.
Read consecutive digits 0 through 9, stopping at the first non-digit.
Leading zeros do not change the base
endptr: If endptr is not NULL (a.k.a. nullptr), store the address of the first character after the digits in *endptr.
If there are no digits, store the original str
Return Value: Return the converted value, or 0 if there are no digits.
Clamp underflow to INT_MIN and overflow to INT_MAX, but consume all consecutive digits in either case.
The conversion itself must not overflow a signed integer
Do not call atoi, strtol, or another string-to-integer conversion function.
For example, " -17cats" returns -17 with *endptr pointing to c. " +x" returns 0 with *endptr pointing to the original start.
With a 32-bit int, "2147483648tail" returns INT_MAX with *endptr pointing to t.
Before You Begin
Before you begin, take some time to think about what str should be, a pointer to a single character? An array of characters?
What about endptr? Is that a 2D array of characters? Or does it point to a single pointer to character?
To answer this, you should probably read the specification of the function and see how each parameter is relevant. You also might want to take notice that the function has to return the converted value, if any. And it seems to also need notify the user where the conversion has ended as well. In essence it basically needs to return two separate things, and pointers help us do this.
Running and Testing
To compile: run make in 2-strtoi
To run: run ./strtoi and enter one line of text (up to 4,094 bytes)
To test: run make test
Come up with your own test cases too.
The program prints the converted value, the end offset, the remaining text,
and the result of a second call with endptr == NULL.
No digits were converted, so the end pointer stays at the original start.
The call with endptr == NULL still returns the same value.
3. Base Conversion
Focus
Reading digits in different bases, updating a caller’s pointer, and storing results through a pointer to a struct.
Introduction
The same number can be written in different bases.
For example, decimal 26 can also be written as hexadecimal 0x1A or binary 0b11010.
The prefix tells us how to interpret the digits that follow it.
We are going to write a function that recognises the base and converts as many digits as it can.
int parse_str(char *input, char **endptr, number *p);
The following type is declared in student.h:
typedef struct { unsigned long value; char type; // 'h', 'b', or 'd'} number;
Start at the beginning of input.
If it begins with 0x, consume the prefix and read hexadecimal digits.
If it begins with 0b, consume the prefix and read binary digits.
Otherwise, read decimal digits.
The prefixes use lowercase x and b.
Form
Valid Digits
Type
0x<digits>
0 to 9 and uppercase A to F
'h'
0b<digits>
0 and 1
'b'
<digits>
0 to 9
'd'
Convert consecutive valid digits until you reach a character that is not valid for that base,
or the terminating null character.
Set *endptr to point to that character.
Do not change the string.
If you converted at least one digit, store the converted value in p->value,
store the type in p->type, and return 0.
An invalid character after valid digits does not make the conversion fail.
For example, 0x1AG succeeds with value 26 and type 'h',
and *endptr points to the G.
If you could not convert any digits, return -1 and leave both fields of *p unchanged.
Still set *endptr to the first character after any recognised prefix.
For 0xG, it points to G; for 0b2, it points to 2.
For -123, it points to -.
An empty string or a prefix with no digits, such as 0x, fails with *endptr pointing to the terminating null character.
The input has no leading spaces.
Do not accept a + or - sign or skip characters before converting.
We guarantee that the value of the converted digits fits in an unsigned long.
The input may be empty or contain characters that cannot be converted.
All three pointers are valid, and the output variables are separate from the input string.
You do not need to allocate or free memory or print anything.
Implement the conversion yourself without calling library conversion functions such as strtol, strtoul, or sscanf.
Running and Testing
To compile: run make in 3-base-conversion
To run: run ./parse
To test: run make test
Enter the input string on one line.
We handle reading the string and calling your function.
The program prints the return status, followed by the value and type if conversion succeeded.
It then prints the end offset, which is the number of characters before *endptr,
and the remaining text inside brackets.
An empty pair of brackets means that *endptr points to the terminating null character.