Section 3: Sanitizers #

In this section, we will look at programs involving wild writes and discuss whether or not the sanitizer can identify them.

You can find the code for this section here.

Question 1: Wild Writes #

Quick questions:

  1. What are sanitizers useful for?
  2. What is a wild write?

Jack is practicing allocating memory dynamically by malloc’ing space for his favorite number using the following program:

int main() {
    // make a 4-byte allocation for an int, set the value to 42
    int* fav_num = (int*)malloc(sizeof(int));
    fav_num[0] = 42;
    
    // print the address of the allocation
    printf("fav_num: %p\n", fav_num);
    ...
}

Later, his friend James also wants to write his favorite number in the same program, but he wants to use Jack’s allocation to do so.

Question 1A. James tries the following methods. What happens in each of these cases?

  1. fav_num[0] = 55;
  2. fav_num[2] = 55;
  3. *(fav_num + 2) = 55;

Question 1B. After running option C, James leaves before checking if it passes the sanitizer. Jack comes back and tries to run his code. To his surprise, he finds the following sanitizer error:

Question1_Error

What does this tell us about what happened?

Question 1C. What happens when we free fav_num? What happens if we don’t free it?

Question 2: Sanitizer Limitations #

Frustrated due to not being able to get past the sanitizer, James starts plotting ways to outsmart the sanitizer.

int main() {
    // make a 4-byte allocation for an int, set the value to 42
    int* fav_num = (int*)malloc(sizeof(int));
    fav_num[0] = 42;
    
    // make a 4-byte allocation for another int, set to 999
    int* fav_num2 = (int*)malloc(sizeof(int));
    fav_num2[0] = 999;
    
    // print the addresses of the allocations.
    printf("fav_num: %p\n", fav_num);
    printf("fav_num2: %p\n", fav_num2);
    ...
}

Question 2A. This program prints the following output.

fav_num: 0x502000000010
fav_num2: 0x502000000030

Is it possible to change the value at fav_num2 by only using fav_num’s address? If so, how?

Question 2B. Is this a wild write? Will this pass the address sanitizer? Why or why not?


Creative Commons Licence This work is licensed under a Creative Commons Attribution 4.0 International License.