April 13, 2026
Homework 8 due tonight on Gradescope
Homework 9 available soon
Lab 10 tomorrow: Memory Errors
List example
malloc man page
calloc, realloc
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 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
Garbage - memory on the heap our code will never use again
Weird: defined in terms of the future!
Compiler can’t figure out when to free for you
Garbage Collector - frees garbage “automatically”
Unreachable memory - memory on heap that is unreachable through pointers on the stack (or reachable by them)
Subset of all the garbage
Identifiable!
Takes resources to work
Very popular - most languages have garbage collectors
Java, Python, C#, ...
Common Memory Bugs (reading)
More on man pages
char *strsep(char **s, const char *d);