ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory
Dynamic vs Static Allocation Dynamic On the heap Amount of memory chosen at runtime Can change allocated memory during runtime Goffin – ENEE150 Static On the stack Amount of memory chosen at compiletime Memory is allocated for entirety of runtime
Dynamic Memory Motivation More optimized data structures Optimal memory usage More powerful data structures overall Linked lists, binary search trees, etc. Goffin – ENEE150
Dynamic Allocation A few possible functions to allocate memory Three main ones: void *malloc(int) most important!!! void *calloc(int, int) void *realloc(void *, int) These functions are all in stdlib.h Goffin – ENEE150
Malloc Parameter determines how many contiguous bytes of memory to allocate % of time you use sizeof( ) Good to explicitly cast output of malloc, but not necessary Example: int *x = (int *)malloc(sizeof(int)); Allocates one “integer size” of memory and stores the address of the first byte to the pointer x Explicit cast with (int *) If you want an array, multiply sizeof(int) by array size Goffin – ENEE150
Notes about Malloc When there is no memory, malloc will return a NULL pointer ALWAYS check for this, otherwise program will go haywire Should use free() for all dynamically allocated memory Goffin – ENEE150
Calloc and Realloc Calloc assumes you want an array and takes two arguments: size of one element and number of elements int *a = (int *)calloc(sizeof(int), 5); // allocates memory for int array of size 5 Realloc takes dynamically allocated memory and changes how much of it there is Good for increasing/decreasing length of arrays, for example int *b = (int *)realloc(a, 3); // returns pointer to a but with int array of only size 3 Goffin – ENEE150
Intro to Linked Lists Essentially a more dynamic array! Goffin – ENEE150
Some Linked List Vocab Node Each element in the list: stores data and a “next pointer” Head pointer Points to first element in the linked list Is NULL for an empty list Next pointer Pointer in each node that indicates the next node in the list Is NULL for the last element in the list Tail pointer (if applicable) Points to last element in the linked list Is NULL for an empty list Goffin – ENEE150
Defining a linked list Use a struct to define a single node in the list typedef struct node_type{ // type of data depends on application! int data1; float data2; // NEXT POINTER, SUPER IMPORTANT struct node_type *next; } node, *pnode; Goffin – ENEE150
Starting a linked list int main(void){ pnode head = NULL; head = (pnode)malloc(sizeof(node)); head->next = NULL; } A single node is allocated Next pointer is NULL, indicating that the node is the last (and only) node in the list Goffin – ENEE150