Module 13: C Language Dynamic Memory Flashcards
dynamic
means “at run-time” (not “at compile-time”); compiler does not have enough information to make a final decition
size_t
a type_def type for an unsigned int
void* malloc(size_t size)
returns a pointer to a region on the heap of size bytes. if it’s successful, space is contiguous. if a heap can’t fulfill request, returns NULL, think of it as creating a reservation for a region of memory that only you can write to, until you call free() and release that reservation
void free(void* ptr)
clears the reservation for address pointed to by ptr and for all the rows initially reserved by the corresponding call to malloc(). example: you ask malloc() for 6 rows. when you call free, it will release the reservation on those six rows
sizeof()
an operator in C that will compute the size of the operand; works on any data type, even structs
memory leak
memory on heap you no longer have a reference to. example: int* my_pointer = malloc(4). my_pointer is a reference to the memory you have reserved. but if you then alter it: my_pointer = NULL, you have lost the only reference you had to your reservation on the heap. now you can never return to that region or even release it using free()
linked list
a type of data structure itself, the purpose of which is to “link” groups of data together. we call the “groups” nodes in the context of a linked list
declaration
when you describe something to the compiler but don’t actually ask for space for it
header file
must end in .h but can only contain “declarations” and not “definitions”
steps for malloc():
char str;
str = (char) malloc(10);
strcpy(str, “OMCIT593”);
steps for free()
remember: each call to malloc() requires a corresponding call to free()
advantages of linked lists
- growth of the list can be dynamic (occur while programming is running)
- make efficient use of memory
- shrinking/reordering our list can also be dynamic
disadvantages of linked lists
pointer and memory management are tricky
more difficult to find things, i.e., traverse the list
memory leaks
most common cause:
- you were done with memory you had allocated
- then you overwrote the last pointer that pointed to it
- but you forgot to call free() on it first
block is gone (cannot be reallocated) for the duration of the program
if you do this repeatedly, your program won’t have heap anymore!
garbage collection
helps avoid leaks while saving you from having to call free()
“reclaims” everything in heap that is not pointed to
C does not have this (Java does!)