Some Learning Notes of CS110L, based on course in 2020 spring that provides video as well as slides.
Exercise
1. Memory Safety Pre-class exercise
Link
Code here
1 |
|
Find 7 bugs:
1. The whole vec_push function does not check if vec is NULL
Similarly, vec_free does not check it, which cause accessing a null pointer
Additional information:
From here we knows thatmalloc(0)returns either a null pointer or a unique pointer, so it might works.
Also,free(NULL)has no problem at least because forfree, if ptr is a null pointer, no action shall occur.
In linux glibc,malloc(0)always returns a returns a unique pointer value that can later be successfully passed to free(). (See man 3 free)
2. capacity growth fails on initial capacity = 0
1 | Vec* vec_new() { |
So that the capacity is always 0, and never malloc any size of memory.
3. Wrong allocation size
1 | int new_capacity = vec->capacity * 2; |
The right size of new_data should be new_capacity * sizeof(int)
4. old vec->data is never freed
5. free order
1 | void vec_free(Vec* vec) { |
vec is freed before freeing its data
6. vec_push does not actually checks the size limit
1 | if (vec->length == vec->capacity) |
The length is lastIndex + 1, but it is used as the last index, exceeding the size limit
7. vec_new returned vec lives too short
1 | Vec* vec_new() { |
