Skip to main content
Logo image

Dive Into Systems: Exercises

Section 2.6 Strings and the String Library

Checkpoint 2.6.1. Strings and char.

    Given the following variable declarations, which of the following lines are syntactically valid ways that character and string types can interact?
    char c, s[20];
  • c = s[0];
  • s = c;
  • c = "A";
  • s = 'A';
  • c = 'A';
  • s[0] = c;
Hint 1.
There is no string type; instead, strings are implemented as arrays of chars. You can’t simply interchange strings and chars in a line of code, as they are fundamentally different under the hood.
Hint 2.
Character literals use single quotes, like: ’A’. String literals use double quotes, like: "A".

Checkpoint 2.6.2. The strlen function.

What will strlen("Hello!") return?
Hint.
The null character at the end of a string takes up a byte of memory, but it does not count for the string length.

Checkpoint 2.6.3. Storing Strings.

Suppose you want to store this string: "Hello!" How many bytes do you have to pass to malloc to allocate enough memory to store it?
Hint 1.
Each character takes up one byte of memory.
Hint 2.
Don’t forget the null character at the end of the string takes up one byte of memory!

Checkpoint 2.6.4. Storing Strings and strcat.

Suppose you have the strings "Hello" and "World" and you strcat them together. How many bytes are needed to store the result?
Hint.
Recall that strcat concatenates two strings together.

Checkpoint 2.6.5. Code safety.

    Which of these functions is a safer alternative to strcpy?
  • strncpy
  • strtok
  • ststr
  • sprintf
Hint.
There is a version of strcpy that adds safety by passing in an N value that is the maximum size to copy, which is usually the size of the destination string.

Checkpoint 2.6.6. Dynamic String Concatenation.

Put these lines of code in order to successfully create the string "Hello World" (held in result) after the code finishes.
Hint.
Think about whether you should do a string copy or a string concatenation first.

Checkpoint 2.6.7. String overflow and undefined behavior.

Hint.
There is not enough room in most of the the arrays to copy any additional characters into them. This is a common mistake that new C programmers make.

Checkpoint 2.6.8. Built-in Character Functions.

Checkpoint 2.6.9. Uppercaseifying a string.

Write a function called uppercaseify that takes a string parameter and modifies the string’s letters to be all uppercase.
So a call to uppercaseify passing the string "yo ho ho!" would modify the string to be "YO HO HO!".
Answer.
Here is a sample solution:
void uppercaseify(char *str) {
    int i, len;
    
    if(str == NULL) {
        return; //error handling
    }
    len = strlen(str);
    for (i = 0; i < len; i++) {
        str[i] = toupper(str[i]);
    }
}