April 8, 2026
Homework 8 due Monday on Gradescope
header example
string.h
variadic functions
int *makeArray() {
int answer[5];
return answer;
}
void setTo(int *array, int length, int value) {
for(int i=0; i<length; i+=1)
array[i] = value;
}
int main(int argc, const char *argv[]) {
int *a1 = makeArray();
setTo(a1, 5, -2);
return 0;
}
The heap: unorganized memory for our data
Most code we write will use the heap
Not a heap data structure...
void *malloc(size_t size);
Ask for size bytes of memory
Returns a (void *) pointer to the first
byte
It does not know what we will use the space for!
Does not erase (or zero) the memory it returns
What is the closest thing to malloc in Java?
malloc man page
malloc Exampletypedef struct student_s {
const char *name;
int credits;
} student;
student *enroll(const char *name, int transfer_credits) {
student *ans = (student *)malloc(sizeof(student));
ans->name = name;
ans->credits = transfer_credits;
return ans;
}Freeing memory: free
void free(void *ptr);
Accepts a pointer returned by malloc
Marks that memory as no longer in use, available to use later
You should free() memory to avoid memory
leaks