Week 7 Flashcards
What do we use to reference memory in the heap?
Pointers
Who assigns memory?
The operating system
The OS gets memory back when the program ends, but what is good programming practice?
To return it yourself
What do we call getting memory from the heap in C?
memory management.
What do we need to include for memory management?
stdlib.h
How do we determine the number of bytes to request?
sizeof() function
C lets you use a pointer as if it was an array. How do we access an element beyond where the pointer is pointing?
Using the […] notation to access elements beyonce where the pointer is pointing.
a_pointer[5] = 20;
A common error with data structures and malloc is that the caller doesn’t allocate the space for the top structure. How do we write this properly?
bool stack_initialize(stack_t*the_stack){} main() { stack_t the_stack; stack_initialize(&the_stack); }
A solution to the problem of a caller not allocating space is to do what?
Make the data structure responsible for all its space
What is an alternative to malloc?
calloc
Once allocated, does space in the heap change size?
Only if you ask it to change size
After using realloc, any data in the previous space is copied into a new space. Are previous pointers into the old space still valid?
No, they’re no longer valid. You’re not guaranteed to get back a pointer to the same pace as before.
How do we return space to the heap with a function?
void free(void *memory_to_return);
What are the two main options for realloc?
Grow in place if possible
Copy to a new location if necessary
Free does not clean up your pointer. How do we avoid mistakes?
Don’t keep using the pointer. You could be accessing memory that is given to another data structure!