0% found this document useful (0 votes)
41 views54 pages

Database Programming: Lecture 3: Heaps & Memory Management By: Dr. Ahmad Barghash

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

Database Programming: Lecture 3: Heaps & Memory Management By: Dr. Ahmad Barghash

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

Database

programming
Lecture 3: Heaps & Memory management
By: Dr. Ahmad Barghash
Where to start?
Linear or Nonlinear

• (Revision note from data structures)Lists,


stacks, and queues are considered linear
structures where one item follows another.
• Trees are considered non-linear as:
• Multiple items can follow one item.
• Number of items following another might
vary
Trees GOOGLE

A
• Distributes data to parent and child nodes.
• Represent family genealogies. B

• Can represent priority queues. C


• Provides fast access information in a database.
D
Ali
E

Wears Eats Drinks

Jeans Shirts Apples Banana Bread Water Cola


Structure of Trees
• Elements (here letters) are called nodes.
• Arrows are called edges.
• Topmost node (here A) is called root.
• Bottom nodes with no edges (here B,D,M, etc) are called leaves (0 children).
• Parent-child relations. F is the parent of L and L is the child of F.

Is it really a tree??
C F R
CS trees are upside-down

B D M L K S Q
Paths, Height, and Depth

• Paths is any sequence of (1 or more) connected nodes for example {A,C,B}, {F,M}, or {S}
• Length of a path is the number of nodes in it
• Longest path from root to leaf is considered the height of that tree (here 3)
• Depth of a node is the length from the root to that node (Depth of L is 3)

C F R

B D M L K S Q
Subtrees

• Subtree of a node is one of the children and its descendants (nodes reached from
it).
• C,B,D is one subtree of A A
• K,Z is the subtree of F

C F R

B D M L K S Q

Z
Binary search trees (BST)
• A tree where each node has 0, 1, or 2 children
• Children are labeled either left or right
• Nodes have 2 pointers (left and right)
• Each node is larger than all nodes in the left subtree and smaller (or equal in some
developments) than all nodes in the right subtree

E 15

C R 5 18

B D M Q 3 12 16 20
Let's build one
• Build a BST for this sequence of values 4,2,3,6,5,7,1

2 6

1 3 5 7
Let's build another

1
• Build a BST for this sequence of values 1,2,3,4,5,6.
2

6
And another one
• Build a BST for this sequence of values 50,2,3,40,55,66,120,1,0,77.

50

2 55

1 3 66

0 40 120

77
Heaps A heap is a certain kind of
complete binary tree.
Heaps Root

• A heap is a certain kind of complete binary tree.

When a complete
binary tree is built,
its first node must be
the root.
Heaps
• Complete binary tree.

The second node is


always the left child
of the root.
Heaps
• Complete binary tree.

The third node is


always the right child
of the root.
Heaps
• Complete binary tree.

The next nodes


always fill the next
level from left-to-right.
Heaps
• Complete binary tree.

The next nodes


always fill the next
level from left-to-right.
Heaps
• Complete binary tree.

The next nodes


always fill the next
level from left-to-right.
Heaps
• Complete binary tree.

The next nodes


always fill the next
level from left-to-right.
Heaps
• Complete binary tree.
• A heap is a certain kind of complete binary
tree.

45

35 23
Heaps
27 21 22 4

19
Each node in a heap
contains a key that
can be compared to
other nodes' keys.
• A heap is a certain kind of complete binary
tree.

45

35 23
Heaps
27 21 22 4

19
The "heap property"
requires that each
node's key is >= the
keys of its children
• Put the new node in the next available spot.
• Push the new node upward, swapping with its parent
until the new node reaches an acceptable location.
Adding a
Node to a 45
Heap
35 23

27 21 22 4

19 42
• Put the new node in the next available spot.
• Push the new node upward, swapping with its parent
until the new node reaches an acceptable location.
Adding a
Node to a 45

Heap 35 23

42 21 22 4

19 27
• Put the new node in the next available spot.
• Push the new node upward, swapping with its parent
until the new node reaches an acceptable location.

Adding a
Node to a 45

Heap 42 23

35 21 22 4

19 27
• The parent has a key that is >= new node, or
• The node reaches the root.
• The process of pushing the new node upward is
called reheapification upward.

Adding a 45
Node to a
Heap 42 23

35 21 22 4

19 27
• Move the last node onto the root.

45

Removing the
Top of a Heap 42 23

35 21 22 4

19 27
• Move the last node onto the root.

27
Removing the
Top of a Heap 42 23

35 21 22 4

19
• Move the last node onto the root.
• Push the out-of-place node downward,
Removing the Top swapping with its larger child until the new
node reaches an acceptable location.
of a Heap
27

42 23

35 21 22 4

19
• Move the last node onto the root.
• Push the out-of-place node downward,
Removing the Top swapping with its larger child until the

of a Heap new node reaches an acceptable location.

42

27 23

35 21 22 4

19
• Move the last node onto the root.
• Push the out-of-place node downward, swapping with
its larger child until the new node reaches an
acceptable location.

Removing 42

the Top of a 35 23
Heap
27 21 22 4

19
• The children all have keys <= the out-of-place
node, or
• The node reaches the leaf.
• The process of pushing the new node downward is
called reheapification downward.

Removing
42
the Top of a
Heap 35 23

27 21 22 4

19
Implementing a Heap
• We will store the data from the nodes in a partially-filled array.
42

35 23

27 21

An array of data
Implementing a Heap
• Data from the root goes in the first location of the array.

42

35 23

27 21

An array of data 42
Implementing a Heap
• Data from the next row goes in the next two array locations.
42

35 23

27 21

An array of data 42 35 23
Implementing a Heap
• Data from the next row goes in the next two array locations.
42

35 23

27 21

An array of data 42 35 23 27 21
Implementing a Heap
• Data from the next row goes in the next two array locations.
42

35 23

27 21

An array of data 42 35 23 27 21

We don't care what's in


this part of the array
Important Points about the Implementation

• The links between the tree's nodes are not actually stored as pointers,
or in any other way. 42
• The only way we "know" that "the array is a tree" is from the way we
manipulate the data.
35 23

27 21

An array of data 42 35 23 27 21
Summary

• A heap is a complete binary tree, where the entry at each node is greater than or equal
to the entries in its children.
• To add an entry to a heap, place the new entry at the next available spot, and perform a
reheapification upward.
• To remove the biggest entry, move the last node onto the root, and perform a
reheapification downward.
Reference

• Presentation copyright 2010 Addison Wesley Longman, Colorado university


Buffer management and
memory allocation
Memory allocation
• There are essentially two types of memory allocation:
• Static – Done by the compiler automatically (implicitly).
• Global variables or objects -- memory is allocated at the start of the
program, and freed when program exits; alive throughout program
execution.
• Can be access anywhere in the program.
• Local variables (inside a routine) – memory is allocated when the routine
starts and freed when the routine returns.
• A local variable cannot be accessed from another routine.
• Allocation and free are done implicitly.
• No need to explicitly manage memory is nice (easy to
work with) but has limitations!
• Using static allocation, the array size must be fixed.
• Once allocated, memory cannot be resized.
• There are essentially two types of memory allocation:
• Wouldn’t it be nice to be able to have an array whose
size can be adjusted depending on needs.
• Dynamic memory allocation deals with this
situation.

Memory • Dynamic – Done explicitly by programmer:

allocation • Programmer explicitly requests the system to


allocate memory and return starting address of
memory allocated.
• This address can be used by the programmer to
access the allocated memory.
• When done using memory, it must be explicitly
freed.
• Function prototype:
void *malloc(size_t size)

• Description:
• reserves in memory the number of bytes
specified in size.
• returns the start address of the new block of
malloc() reserved memory.
• do not lose this!
Function
• Important points:
• once allocated, memory is reserved until:
• it is freed explicitly, using :
• free() function.
• program termination.
• If you lose a pointer to dynamically allocated
memory, it stays reserved anyway.
double *a;
a = (double *) malloc(sizeof(double));
Example *a = 3.14;
printf("%lf\n", *a);
free(a);
What do we call this?

double *a;
a = (double *) malloc(sizeof(double));
a = (double *) malloc(sizeof(double));

Memory leak

We need to free the memory


• Function prototype:
void *calloc(size_t nitems, size_t size)

• Description
• Reserves in memory n items, each the
number of bytes specified in size
calloc() Function • Returns the start of the new block of
reserved memory

• Example:
double *a;
a=(double *) calloc (70, sizeof(double));
• Attempts to resize the memory block pointed to by ptr.
• Function prototype:
• void *realloc(void *ptr, size_t size)
realloc() • ptr: Pointer to memory block to be reallocated
• Size: the new size of the memory block in bytes
Function
• Return Value
This function returns a pointer to the newly allocated
memory, or NULL if the request fails.
• Dynamically allocated memory can be
accessed:
• Through pointers
• Using array notation
Accessing
Dynamically
• Example:
Allocated int *A;
Memory A=(int *) calloc(5, sizeof(int));
A[0]=8;
*(A+2)=3;
A[3]=9;
Deallocating Dynamically
Allocated Memory

• You must deallocate (release) all memory that you allocate.

• Why?
• You can not reuse memory that’s allocated.
• No one else will clean your mess 

• Function prototype
void free(void *ptr) The Compiler would say….

• Description:
• Releases the memory pointed to by ptr.
Memory Leaks

Whats a memory leak? Whats so bad about this?


When you lose pointer to dynamically allocated You lose access to data in memory.
memory. Amount of memory available is not infinit.
When you forget to deallocate dynamically You will lose certain amount of memory till the
allocated memory. end of the program’s lifetime.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {

char name[100];
char *description;
strcpy(name, "DB Programming");
/* allocate memory dynamically */
What is the description = malloc( 200 * sizeof(char) );

output here
if( description == NULL ) {
fprintf(stderr, "Error - unable to allocate required
memory\n");
}
else {
strcpy( description, "Salam shabab");
}
printf("Name = %s\n", name ); The output is:
printf("Description: %s\n", description );
Name = DB Programming
Description: Salam shabab
free(description);

}
#include <stdio.h>
#include <stdlib.h>

int main() {
char *str;

/* Initial memory allocation */


str = (char *) malloc(15);
strcpy(str, "tutorialspoint");
printf("String = %s, Address = %u\n", str, str);

What is the /* Reallocating memory */

output here?
str = (char *) realloc(str, 25);
strcat(str, ".com");
printf("String = %s, Address = %u\n", str, str);

free(str);

return(0);
}

The output is:


String = tutorialspoint, Address = 355090448
String = tutorialspoint.com, Address = 355090448
What is the output here
#include <stdio.h> /* suppose you want to store bigger description */
#include <stdlib.h> description = realloc( description, 100 * sizeof(char) );
#include <string.h>
if( description == NULL ) {
int main() { fprintf(stderr, "Error - unable to allocate required memory\n");
}
char name[100]; else {
char *description; strcat( description, “Students of DB");
}

strcpy(name, "Zara Ali");


printf("Name = %s\n", name );
printf("Description: %s\n", description );
/* allocate memory dynamically */
description = malloc( 30 * sizeof(char) );
/* release memory using free() function */
free(description);
if( description == NULL ) { }
fprintf(stderr, "Error - unable to allocate required memory\n");
}
The output is:
else {
Name = Zara Ali
strcpy( description, “DB student.");
Description: DB student.Students of DB
}

You might also like