0% found this document useful (0 votes)
34 views45 pages

ICT1002 W11 LEC Dynamic Memory Allocation

This document discusses dynamic memory allocation and linked lists. It begins by explaining why dynamic allocation is needed when the amount of memory needed is not known at compile time. It then covers the three steps to dynamic allocation: including stdlib.h, using malloc or calloc to request memory, and freeing memory with free. Examples are given showing how to allocate memory for arrays and strings. The document finishes by providing an overview of linked lists, including how to create nodes and link them together to form a simple linked list.

Uploaded by

CH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views45 pages

ICT1002 W11 LEC Dynamic Memory Allocation

This document discusses dynamic memory allocation and linked lists. It begins by explaining why dynamic allocation is needed when the amount of memory needed is not known at compile time. It then covers the three steps to dynamic allocation: including stdlib.h, using malloc or calloc to request memory, and freeing memory with free. Examples are given showing how to allocate memory for arrays and strings. The document finishes by providing an overview of linked lists, including how to create nodes and link them together to form a simple linked list.

Uploaded by

CH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

DYNAMIC MEMORY

ALLOCATION
DR FRANK GUAN
ICT1002 – PROGRAMMING FUNDAMENTALS
WEEK 11
SELF-ASSESSMENT FOR WEEK 10

2
Agenda
1. Dynamic memory allocation
2. Linked lists

3
RECOMMENDED READING
Paul Deitel and
Harvey Deitel, C:
How to Program,
8th Edition,
Prentice Hall,
2016
– Chapter 12: C
Data Structures

4
DYNAMIC MEMORY ALLOCATION

5
WHY DYNAMIC MEMORY ALLOCATION?
include <stdio.h>
NUM_STUDENTS has to
#define NUM_STUDENTS 10
be defined at compile
int main() { time
int grades[NUM_STUDENTS];
int i;

for (i = 0; i < NUM_STUDENTS; i++) {


printf("Grade for student %d: ", i + 1);
scanf("%d", &grades[i]);
}

return 0; This loop reads the


grades for students
}

What happens if we do not know how many


students we have in advance?
6
We need DYNAMIC
memory allocation

7
MEMORY ALLOCATION

Compile time Run time (DYNAMIC)


(STATIC) Allocation Allocation
Memory for named variables Memory allocated during run
is allocated by the compiler. time is allocated space in a
program segment known as
The exact size and type of the heap or the free store.
storage must be known at
compile time. The exact amount of space
or number of items does not
have to be known by the
compiler in advance.
DYNAMIC MEMORY ALLOCATION
Three steps to dynamic memory allocation:

1. include #include <stdlib.h>

Use malloc or calloc to request memory.

2. malloc int *ptr = (int *)malloc(sizeof(int)*N);

Free up the memory when no longer

3. free
needed.
free(ptr);

9
MALLOC AND CALLOC
malloc allocates a block of memory with a
given number of bytes
int *ptr = (int *)malloc(sizeof(int) * N);

calloc allocates a block of memory with


space for a given number of elements,
and sets them to zero
int *ptr = (int *)calloc(N, sizeof(int));

malloc VS calloc
https://stackoverflow.com/questions/1538420/difference-between-malloc-and-calloc
10
MALLOC AND CALLOC
malloc and calloc return a void pointer
to the start of the allocated memory
• it must be cast to the appropriate type before
use

• it is often used like an array

• if not enough memory is available, the pointer


has the special value NULL

int *grades = (int *)malloc(num_students * sizeof(int));


for (i = 0; i < num_students; i++)
grades[i] = …;

11
THE SIZEOF OPERATOR
To be able to allocate memory dynamically,
we need to tell the compiler the size of
memory we need at runtime.

The sizeof operator returns the number of


bytes required to hold a type.
• E.g.
– sizeof(char) evaluates to 1
– sizeof(int) evaluates to 2, 4 or 8 depending on the
word size of the compiler

12
THE SIZEOF OPERATOR

This gives the size


of an integer.

int size = sizeof(int) * 4;
printf("size of 4 integers is: 
  %d bytes\n", size);

13
THE SIZEOF OPERATOR

This gives the size


of 4 integers.

int size = sizeof(int) * 4;
printf("size of 4 integers is:
  %d bytes\n", size);

Output:
size of 4 integers is: 16 bytes

14
THE SIZEOF OPERATOR
The sizeof operator can also be used with
user-defined types:

typedef struct {
  int id;
  char name[25];
} Student;

printf("The size of a Student record is:
  %d bytes\n", sizeof(Student));

15
FREE
free de-allocates memory previously
allocated by malloc or calloc
• all memory allocated by malloc or calloc
should eventually be free’d

• this allows the memory to be re-used

• failure to de-allocate memory is called a


memory leak

• a leaking program will use up more and more


memory over time, and eventually crash

16
EXAMPLE
#include <stdio.h>
#include <stdlib.h>
With dynamic memory
int main() { allocation, we can set the
int *grades;
number of students at run
int num_students; time.
/* ask how many grades need to be stored */
printf("How many students are in your class? ");
scanf("%d", &num_students);

/* allocate enough space to hold num_students integers */
grades = (int *)malloc(num_students * sizeof(int));
if (grades == NULL) {
printf("Out of memory.");
return 1;
}

/* read the grades */ If there is not enough


for (int i = 0; i < num_students; i++) { memory, malloc returns
printf("Grade for student %d: ", i + 1);
scanf("%d", &grades[i]);
NULL.
}

/* de‐allocate memory */
free(grades);

return 0; Use free to de-allocate memory


when it is no longer required.
} 17
DYNAMIC MEMORY ALLOCATION
STRINGS
/* allocate enough space to hold num_students strings */
char **names = (char **)malloc(num_students * sizeof(char *));
if (names == NULL) {
printf("Out of memory.");
return 1;
}
names is an array of
for (i = 0; i < num_students; i++) {
/* read the name */
pointers to characters.
printf("Name of student %d: ", i + 1);
fgets(buf, MAX_NAME, stdin);

/* copy the name into the array */
int length = strchr(buf, '\n') ‐ buf;
names[i] = (char *)calloc(length + 1, sizeof(char));
if (names[i] == NULL) {
printf("Out of memory.");
return 1;
}
strncpy(names[i], buf, length); Allocate space for each
} string according to its
length.
/* de‐allocate memory */
for (i = 0; i < num_students; i++)
free(names[i]);
free(names);

Invoke free for each allocated


block of memory.
18
LINKED LISTS
LINKED LISTS

12 13 5 7 X

head

A linked list is a linear collection of


self-referential structures, called
nodes, connected by pointers,
called links.

20
Arrays need
contiguous memory
slots. With a linked list,
you can optimise
Array memory by linking data
at different memory
locations.
Why are you teaching
us Linked Lists? We
are happy with
arrays!

Linked list
21
SELF-REFERENTIAL
STRUCTURES A self-
referential
structure
typedef struct node_struct {
int data; contains a
struct node_struct *next;
} Node;
pointer 
member that
points to a
structure of the
same type
22
SELF-REFERENTIAL
STRUCTURES Self-referential
structures can
be linked
together to
form useful
data structures
such as linked
lists, queues,
stacks and
trees.
23
How do you create two nodes and
link node1 to node2?

node1 node2

24
CREATING A LINKED LIST
int main() {

Node node1 = { 15, NULL };
Node node2 = { 10, NULL };
node1.next = &node2;

node1 node2

25
ACCESSING DATA IN A LINKED LIST
int main() {

Node node1 = { 15, NULL };
Node node2 = { 10, NULL };
node1.next = &node2;

printf("node1.data = %d\n", node1.data);
printf("node1.next = %p\n", node1.next);

Use the dot “.”


notation for non-
pointer variables
26
ACCESSING DATA IN A LINKED LIST
int main() {

Node node1 = { 15, NULL };
Node node2 = { 10, NULL };
node1.next = &node2;

Node *node_ptr = &node1;
printf("node1.data = %d\n", node_ptr‐>data);
node_ptr = node_ptr‐>next;
printf("node2.data = %d\n", node_ptr‐>data);

}
Use the arrow
“‐>” operator for
pointer variables
27
ACCESSING DATA IN A LINKED LIST

12 13 5 7 X
Subsequent nodes are
head accessed via the link in By convention: the
each node. link pointer in the
A linked list is accessed last node points to
via a pointer to the first NULL.
node (head).

28
LINKED LIST ARRAY

Dynamic STATIC
The length of the list can increase or The size of an array cannot be altered once
decrease as necessary. memory is allocated.

Cannot be full easily Arrays can


A linked list becomes full only when the
system has insufficient memory to satisfy
dynamic storage allocation requests. become full.
Arrays can be declared to contain more
GOOD when size is elements than the number of data items
unpredictable expected, but this can waste memory.

29
LINKED LIST OPERATIONS

Search/update

Insert

Delete

30
LINKED LIST OPERATIONS Search

12 13 5 7 X

head temp

temp is a pointer to the first node of


the list.

How do we move temp to the node


containing 5?

31
LINKED LIST OPERATIONS Search

12 13 5 7 X

head temp

temp = temp‐>next;

Using the next pointer


32
LINKED LIST OPERATIONS Search

12 13 5 7 X

head temp

temp = temp‐>next;
temp = temp‐>next;

Using the next pointer


33
LINKED LIST OPERATIONS
Insert
100 X 12 13 5 7 X

new_node head

Node *new_node = (Node *)malloc(sizeof(Node));
new_node‐>data = 100;
new_node‐>next = NULL;

How do we insert new_node at the


beginning of the list?
34
LINKED LIST OPERATIONS
Insert
100 12 13 5 7 X

new_node head

new_node‐>next = head;

1. Link the new node to the old head.

35
LINKED LIST OPERATIONS
Insert
100 12 13 5 7 X

head

new_node‐>next = head;
head = new_node;

2. Move the head to the new node.

36
LINKED LIST OPERATIONS Delete
12 13 5 7 X

head node_ptr

How do we delete the node pointed to


by node_ptr?
37
LINKED LIST OPERATIONS
Delete
12 13 5 7 X

head prev_ptr node_ptr


Don’t forget
to free the
prev_ptr‐>next = node_ptr‐>next; node if it
was
free(node_ptr); created by
malloc.

How do we get prev_ptr?


38
LINKED LIST OPERATIONS
Delete
12 13 5 7 X

head temp node_ptr

Node *temp = head;
while (temp‐>next != NULL){
if (temp‐>next == node_ptr){
return temp;
}
temp = temp‐>next;
}
39
EXERCISE - 1

Write a function:
Node *search_list(Node *head, int target);

Given a pointer to the head of a linked list,


return a pointer to the first node in the list
whose data is equal to target.

40
EXERCISE - 2

Write a function:
Node *insert_at_head(Node *head,
Node *new_node);

Given a linked list with its head pointer,


insert the node pointed to by new_node to
linked list and return the head pointer to the
list.

41
EXERCISE - 3

Write a function:
Node *delete_node(Node *head, Node
*node_ptr);

Given a linked list with its head pointer,


delete the node pointed to by node_ptr and
return a pointer to the head node.
Why do we need to return a pointer
to the head node?
42
EXERCISE - 4

Write functions that perform each of the


following operations:

print every element in the list

insert an element at the end of list

deallocate the whole list

43
END-OF-WEEK CHECKLIST

Dynamic memory allocation

The sizeof operator

malloc() and free()


Self-assessment (for practice only):
Self-referential structures Socrative: https://b.socrative.com/login/student
Room: ICT1002
Linked lists

Linked lists vs arrays

Searching & updating lists

Inserting into linked lists

Deleting from linked lists

44
ABOUT CLASS TEST
– Date: 21 Nov 2019 (Thursday)
– Time:
– Seated before 9:00AM
– Start punctually at 9:15AM
– Duration: 45 minutes
– Scope
– Week 8 – Week 11

– Note:
– You are not allowed bring any notes into the test.
– You are not allowed to use any electronic devices.
– You may bring in your calculator.

45

You might also like