Task
Implement the function num_bytes_allocd
- Given a
block_header*to the start of the heap, return the number of bytes that have been allocated - Don’t modify the struct definition at the top of the file
- Don’t modify the
fake_heaps.h,fake_heaps.o, orMakefilefiles
Function Signature
// Given a block_header* to the start of the heap, return the number of
// bytes that have been allocated
//
int32_t num_bytes_allocd(struct block_header* start);Testing
Compiling
- Use the given
Makefileto compile your program- To use the
Makefilejust typemakeinto the terminal (Refer back to Week 3 Lab for more information onMakefiles)
- To use the
Test Cases
- To test your code, you can use the variables
heap1,heap2,heap3,heap4,heap5, which are defined in thefake_heaps.hheader file.- These are pointers to the start of different heaps and have different allocated blocks in each of them
- For example, to use
heap1in testing in yourmainfunction, here’s what it could look like
int main() {
int32_t allocdBytes = num_bytes_allocd(heap1);
printf("Number of alloc'd bytes: %d\n", allocdBytes);
return 0;
}Example
Test Case 1
Input: heap1
Output: 4080 (look into fake_heaps.h to see a diagram of each heap)
Test Case 2
Input: heap3
Output: 1536
Code
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stddef.h>
#include "fake_heaps.h"
struct block_header {
size_t size_status;
};
int32_t num_bytes_allocd(struct block_header* start){
int32_t count = 0;
struct block_header* current = start;
while(current->size_status != 1){
size_t size = current->size_status >> 2;
if(current->size_status % 2 == 1){
count += (size << 2);
}
void* next = (void*)current + (size << 2);
current = (struct block_header*)next;
}
return count;
}