Chap 13(dynamic memory allocation)

8
Dynamic Memory Allocation and Linked Lists Topics Dynamic memory allocation

Transcript of Chap 13(dynamic memory allocation)

Page 1: Chap 13(dynamic memory allocation)

Dynamic Memory Allocation and Linked Lists

Topics Dynamic memory allocation

Page 2: Chap 13(dynamic memory allocation)

Dynamic Memory Allocation The process of allocating memory at run

time is known as dynamic memory allocation.

There are some functions for dynamic memory allocation. These are malloc, calloc, free and realloc.

Page 3: Chap 13(dynamic memory allocation)

Allocating a Block of Memory A block of memory may be allocated using

the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. The form-

ptr = (cast-type *)malloc(byte-size);

ptr is a pointer of type cast-type. Example:

ptr = (int *) malloc(100*sizeof(int));

Page 4: Chap 13(dynamic memory allocation)

Allocating Multiple blocks of Memory Calloc is another memory allocation function

that is normally used for request memory space at run time for storing derived data types such as array and structures. It allocates multiple blocks of storage, each of the same size. The general format-

ptr = (cast-type *)calloc(n,element-size);

Page 5: Chap 13(dynamic memory allocation)

Releasing the used space & Altering the size free function can be used to release the

used space. The format is-

free(ptr); We can change the memory size already

allocated with the help of the function realloc.

ptr = realloc(ptr, newsize);

Page 6: Chap 13(dynamic memory allocation)

Concepts of Linked List A linked list is one kind of list whose order is given

by links from one item to the next. Each structure of the list is called a node and

consists of two fields, one containing the item and the other containing the address of the next item in the list.

A linked list is therefore a collection of structures ordered not by their physical placement in memory but by logical links that are stored as part of the data in the structure itself. The link is in the form of a pointer to another structure of the same type.

Page 7: Chap 13(dynamic memory allocation)

Continue… The structure is represented as:

struct node

{

int item;

struct node *next;

};

Page 8: Chap 13(dynamic memory allocation)

Advantage of Linked List Advantages:

1. Linked list can grow or shrink in size during the execution of a program.2. It does not waste memory space.3. It provides flexibility in allowing the items to be rearranged efficiently.

Limitation:1. The access of any arbitrary item is little cumbersome and time consuming.2. It will use more storage than an array with the same number of items as it has link field.