### Comp111: Operating Systems Classroom Exercise 10 Memory Management Fall 2017

#### group member 1: ____________________________ linux login: ______________ group member 2: ____________________________ linux login: ______________ group member 3: ____________________________ linux login: ______________ group member 4: ____________________________ linux login: ______________ group member 5: ____________________________ linux login: ______________ group member 6: ____________________________ linux login: ______________ group member 7: ____________________________ linux login: ______________ group member 8: ____________________________ linux login: ______________

In class we have studied the buddy system for memory resource management. Let's do some simulation to make sure we understand it. In your simulations, please assume that:

1. no less than 16 bytes can be allocated via malloc (e.g., ia32).
2. the block storage descriptor is 16 bytes, physically located before the bytes to be used, so that the usable memory starts at the descriptor address+16.
3. the block storage descriptor has two 8-byte fields:
• a `next` pointer for use in the free list.
• a `size` integer that is the power of two that represents the block's total size.
E.g., if `size` is 5, then
• total block size is 25 = 32 bytes.
• total usable memory is 25-16 (descriptor) = 16 bytes.
4. `malloc` only calls `sbrk` in units of 8192 bytes, i.e., the call is of the form `sbrk(n*8192)` for n a positive integer.
(This is roughly the implementation of "BSD malloc".)
1. Exactly how much memory is allocated to me if I ask for 800 bytes from `malloc`? Exactly how much memory is added to the heap?
2. Describe exactly what happens when one calls
```
int *foo = (int *)malloc(100*sizeof(int));
```
as the first `malloc` of a program. Assume that `sizeof(int)` is 8 (e.g., on `comp111.cs.tufts.edu`).

3. Describe exactly what happens when one (subsequently) calls `free(foo)`.

4. Describe exactly what happens when one subsequently calls
```int *bar = (int *)malloc(10*sizeof(int));
```
Is `foo`'s memory reused? Why or why not?

5. (Advanced) A very common programming error is to write something equivalent to:
```int *cat = (int *) malloc(sizeof(int));
int *dog = (int *) malloc(sizeof(int));
cat[3]=0;
free(dog); // segmentation fault: core dumped
```
Assuming that ints are 8 bytes, why might this cause a segmentation fault (in some linuxes) when calling `free(dog)`?

6. (Advanced) Malloc doesn't use the buddy system for things larger than a page (8192 bytes = 213). So why do we allocate 8 bytes to store a number between 5 and 13? It would seem that this number would take a total of 4 bits = 1/2 of a byte.