




























































































Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!





























































































Algorithms and Data Structures 1
Dynamic Allocation
Dynamic Lists
Recursion
Abstract Data Types
Trees
Hash Tables
Heap Sort and Priority Queues
Graphs
Graphs Applications
The compiler allocates a predefined quantity of memory for each variable defined in the source program, which depends on the type of the variable and its size.
To make a program more flexible we should be able to:
allocate initial and additional memory when needed free up the allocated memory when it is no more needed
Allocation of memory during execution is called dynamic memory allocation.
The dynamic memory is allocated in a dedicated area of the system called the Heap.
Introduction malloc( ) function calloc( ) function realloc( ) function free( ) function Dynamic 1D Arrays Return an array to the caller String allocation General array allocation Dynamic 2D Arrays Linearization 2D as 2D Notation Deallocation Common errors Pass arrays in functions
char *p1, *p2; p1 = (char ) malloc(sizeof(char)); //allocates memory for a single character p2 = malloc(sizeof(p2));
Allocation of a struct:
struct mys *p1, *p2; p1 = (struct mys ) malloc(sizeof(struct mys)); //allocates memory for a single struct p2 = malloc(sizeof(p2));
Allocation of an array:
char p; p = malloc(100sizeof(char)); //allocates memory for an arr ay of 100 characters
struct node newPtr; newPtr = malloc(nsizeof(struct node)); //allocates memory for n structs
int *p; p = (int ) malloc(1 sizeof(int)); if (p==NULL) { fprintf(stderr, "Memory allocation error\n"); } fprintf(stdout, "Introduce an integer value: "); scanf("%d",p);
Common errors :
int *p1; char *p2;
p2 = malloc(sizeof(int)); //p2 is a pointer to a char p1 = (int) malloc(sizeof(int)); //we must cast to int *, no t to int p1 = (int *) malloc(sizeof(int *)); //int, not int * (we sh ould pass a type, not a pointer)
The function calloc dynamically allocates memory and initializes this memory.
void *calloc(size_t number_of_objects, size_t size); It requires the number of of elements each one with a size It's more array-oriented
Function calloc corresponds to a malloc followed by an initialization phase, which has a linear cost (for a chunk of n slots, calloc has a cost of O(n)). → if the initialization is not required, the function malloc is more efficient.
Comparison :
//calloc int *test; test = calloc(5,sizeof(int)); if (test==NULL) { fprintf(stderr, "Memory allocation error\n");
content is copied, so it's more efficient to ask for a real location of size*2, than size+
The function free deallocates memory , so the memory is returned to the system so that it can be reallocated in the future. This function must only be used to release memory assigned with malloc, calloc and realloc.
Static array cannot be freed
int *p; p = (int ) malloc(nsizeof(int)); free(p); //the area occupied by p is now free
💡 Freed memory cannot be re-used: the programmer does not own it and the operating system can use it as it likes
The number of free in a program should match the number of malloc (or calloc/realloc).
Dynamic 1D Arrays
Dynamic allocation is safer. Disadvanteges of VLA (Variable-Length Arrays):
VLAs are a subset of dynamic allocation It’s unsafe, there is no cecking strategy for the size of the array
Using free reduces the possibility to run out of memory.
They are automatically deallocated once the envirnoment is abandoned, and they cannot be used outside this environment Dynamically allocated arrays can be used outside the functions of definition , by using pointers
Example :
int n, v; //number of elements and pointer to the array fprintf(stdout, "Introduce n: "); scanf("%d",&n); v = (int ) malloc(nsizeof(int)); //allocation of the arra y -> v will point to the array for (int i=0;i<n;i++) { //static array notation printf("v[%d]:",i); scanf("%d",&v[i]); } for (int i=0,int p=0;i<n;i++,p++) { //dynamic array notati on printf("v[%d]:",i); scanf("%d",p); } free(v); //free the memory //in this case calloc is completely useless because actuall y we are initializing the array
Common errors :
char v[10]; char p = malloc(10sizeof(char)); -> sizeof(v) is 10 bytes (actual size of the array) -> sizeof(p) is the size occupied by a pointer, so 8 bytes
int main() { int n, *v = NULL; scanf("%d",&n); arraycreate(v,n);
It is necessary to always reserve space for the termination character ‘\0’.
char str[100+1]; //100 characters char v; v = malloc(strlen(str)+1sizeof(char)); if (v==NULL) {...} strcpy(v,str); free(v);
Strdup function performs allocation and strcpy:
char str[100+1]; //100 characters char *v; v = strdup(str); //perform all the operations free(v);
By using static arrays:
#define N 100
//static arrays struct student { char last_name[N], first_name[N]; int register_number; float average; };
int n; struct student *v; v = (struct student ) malloc(nsizeof(struct student));
for (i=0;i<n;i++) { scanf("%s%s%d%d",ln,fn,&rn,&a); strcpy(v[i].lastname,ln); strcpy(v[i].firstname,fn);
v[i].register_number = rn; v[i].average = a; }
By using dynamic array:
struct student { char *last_name, *first_name; int register_number; float average; };
int n; struct student *v; v = (struct student ) malloc(nsizeof(struct student));
for (i=0;i<n;i++) { scanf("%s%s%d%d",ln,fn,&rn,&a); //allocation of lastname and copy v[i].lastname = (char ) malloc((strlen(ln)+1)sizeof(c har)); strcpy(v[i].lastname,ln); //allocation of firstname and copy v[i].firstname= (char ) malloc((strlen(fn)+1)sizeof(c har)); strcpy(v[i].firstname,fn);
v[i].register_number = rn; v[i].average = a; }
//free the memory from last to first for (i=0;i<n;i++) { free(v[i].last_name); free(v[i].first_name); } free(v);
The linearization can follow two different schemes:
Row-major-order : Rows are allocated one after the otger, with elements contiguous in cells Column-major-order : Columns are allocated one after the otger, with elements contiguous in cells
Row-major-order :
To pass from 2D to 1D:
To pass from 1D to 2D:
The row-major-order scheme is automatically used by any C compiler everytime a multi- dimensional array is defined.
To allocate an array of R pointers to arrays of C elements we must:
Allocate one array of R pointers (each pointer references one entire array of basic elements) Allocate R arrays of C basic elements (one array for each row)
mat = (int ) malloc (rsizeof(int)); //allocation of the array for (int i=0;i<r;i++) { mat[i] = (int) malloc(csizeof(int)); //allocation of each row }
is a value → indicates a single element is a pointer to the row → indicates an array of values is a pointer to the array of pointers
for (i=0;i<r;i++) { free(mat[i]); //deallocation of columns } free(mat); //deallocation of rows
for (i=0;i<r;i++) { mat[i] = (char) malloc(csizeof(char)); } return; }
Finally free memory:
mat = free2d(mat,nr); ... char *free2d(char **m, int r) { int i; for(i=0;i<r;i++) { free(m[i]); } free(m); return NULL; }
Dynamic Lists 1
A list can be seen as a linear sequence of elements: Given an element, we are able to define the successor and the predecessor The operations of the list are based on the position of the elements or their key
In C a linked list is a linear collection of self-referential structures. Each structure is called element and all structures are connected by pointers:
Definition List and array implementation Atomic operations Visit a list Search in a list Head extraction In order extraction Tail extraction Head insertion In-order insertion Tail insertion Dispose a list Common Linked Lists LIFO Lists FIFO Lists Ordered Linked Lists Doubly-linked Lists List of Lists
Dynamic Lists 3
Differently from arrays, lists can grow and shrink in size as the program runs.
Atomic operations Definition of a list in C:
#option 1 typedef struct list_s { int key; //key and data fields ... struct list_s next; //auto-referencing pointer } list_t; #option 2 typedef struct list_s list_t; struct list_s { int key; ... list_t next; };
Allocation of a new node:
list_t *newelement() { list_t e_ptr; //new element e_ptr = (list_t) malloc(sizeof(list_t)); //allocation for the single element
Dynamic Lists 4
if (e_ptr==NULL) exit(1); return e_ptr; //return the pointer to the new element t o the user }
list_t *head, *new; ... head = NULL; //initially the list is empty -> is not pointi ng to any list new = newelement();
The cost is linear:
list_t *p; //p is a pointer that traverses the list p = head; while(p!=NULL) { //exit if the tail is NULL p = p->next; }
#option 1 list_t *p; p = head; while(p!=NULL) { if (value==p->key) { //i look at the key return p; //element found } else { p = p->next; } } #option 2: unique element while((p!=NULL)&&(p->key!=value)) { //the order matter (for example if p is NULL) p = p->next; }