1
12/27/2022
Dynamic memory management
Dynamic memory
2
12/27/2022
Dynamic memory
3
12/27/2022
Dynamic memory allocation
size_t is an alias for unsigned int.
malloc returns a pointer to space for an object of the given size. It returns NULL if the request cannot be satisfied. The space is uninitialized.
returns a pointer to space for an array of n objects of the specified size, or NULL if the request cannot be satisfied. The storage is initialized to zero.
releases the memory pointed by p; p must be a pointer to space allocated dynamically. It does nothing if p is NULL.
4
12/27/2022
Dynamic memory allocation
realloc adjusts the amount of memory allocated to the block to size, copying the contents to the new location if necessary. block must be an allocated memory using dynamic memory functions.
5
12/27/2022
examples
p = (int *)malloc( sizeof(int) );
*p = 10;
printf(“%d”, *p);
free(p);
6
12/27/2022
example
p = (int *) calloc(10, sizeof(int) );
/* now p is the starting address of an array of 10 ints */
p[5] = 10;
7
12/27/2022
Concepts of linked lists
8
12/27/2022
Arrays
9
12/27/2022
lists
10
12/27/2022
Linked list
11
12/27/2022
Item
Item
Item
Structure 1
Structure 2
Structure 3
struct node {
int item;
struct node *next;
};
Linked list of names (in reverse order)
main( )
{
char s[64];
struct node *head = NULL, *new_node;
do{
puts(“enter a name:”);
gets(s);
if(strlen(s) > 0) {
new_node = (struct node *) malloc(sizeof(struct node));
strcpy(new_node->name, s);
new_node -> next = head;
head = new_node;
}
} while(strlen(s) > 0);
}
12
12/27/2022
How to insert in between a linked list
{
struct node *temp;
temp = where ->next;
where->next = &s;
s.next = temp;
}
13
12/27/2022
How to delete from middle
{
struct node *temp;
temp = p ->next ->next;
free(p->next);
p->next = temp;
}
14
12/27/2022
Searching a linked list
{
struct node *temp;
temp = head;
while(temp != NULL) {
if(temp->roll_no == roll_no)
return(temp);
else temp = temp->next;
}
return NULL;
}
15
12/27/2022
Other linked lists
16
12/27/2022
Don’t we have any drawbacks of linked lists ?
17
12/27/2022