lect19
lect19
Partial Specs:
➔ What is each argument precisely? Can arguments be null?
➔ Are pointers to stack data allowed? (what if stack is popped?)
➔ Are cycles in data structures allowed?
➔ Are there min and max sizes of data?
Checking specifications as part of code
● Specs are useful for more than writing code and testing
● Check them dynamically, e.g., with assertions
○ Easy: argument not NULL
○ Harder but doable: list not cyclic
○ Impossible: Does the caller have other pointers to this
object?
Use ‘assert’ in C
Remember this? #include <assert.h>
Unit Testing #include <stdlib.h>
#include "f.h"
Test small components of code // Assert statements will fail with a message
// if not true.
individually int main(int argc, char** argv) {
Freemem: return the given block to the free list, combining it with any adjacent free
blocks if possible to create a single, larger block instead of several smaller ones.
Approach: getting memory blocks
If, a large enough block exists, ‘getmem’ splits the block into an appropriate sized chunk
and pointer to the block
Split it up, yielding a block that will satisfy the request (‘if’ condition)
Note, Initial call to getmem finds it with no memory, and results in ‘else’ condition.
Approach: returning memory
● Freemem gets a pointer to a block of storage and adds it to the free list, combining
it with adjacent blocks on the list.
● Freemem isn't told is how big the block is and must find the size of the block.
● The usual way this is done is to have getmem actually allocate a block of memory
that is a bit larger than the user's request, store the free list node or just the size of
the block at the beginning of that block.
● The returned pointer is actually points a few bytes beyond the real start of the
block.
● When freemem is called, it can take the pointer it is given, subtract the appropriate
number of bytes to get the real start address of the block, and find the size of the
block there.
HW6 : using ‘extern’
● Where does the free list head pointer live?
○ Needs to be accessible in both getmem and freemem implementation .c
files.
● Could put it in a shared header file?
○ But, int x; allocates space for ‘x’ which is bad in a header file.
● Can we DECLARE ‘x’, but not DEFINE it?
○ Yes!: extern int x;
● Then in a .c file, you can actually define it (only in one file!).