[go: up one dir, main page]

0% found this document useful (0 votes)
11 views35 pages

Memory Management: Chapter 3 - Principles of Data Structures Using C by Vinu V Das

Aatif Shahbaz 18 Multiple Block Allocation  malloc( ) allocates a single block of memory.  To allocate multiple blocks of memory, multiple calls to malloc( ) are required. Example: int *ptr1, *ptr2; ptr1 = malloc(10*sizeof(int)); ptr2 = malloc(15*sizeof(int));  Here two blocks of memory are allocated - - First block of 10 integers - Second block of 15 integers  ptr1 and ptr2 will point to the base addresses of these two blocks.  The blocks are not contiguous

Uploaded by

Aamir Chohan
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)
11 views35 pages

Memory Management: Chapter 3 - Principles of Data Structures Using C by Vinu V Das

Aatif Shahbaz 18 Multiple Block Allocation  malloc( ) allocates a single block of memory.  To allocate multiple blocks of memory, multiple calls to malloc( ) are required. Example: int *ptr1, *ptr2; ptr1 = malloc(10*sizeof(int)); ptr2 = malloc(15*sizeof(int));  Here two blocks of memory are allocated - - First block of 10 integers - Second block of 15 integers  ptr1 and ptr2 will point to the base addresses of these two blocks.  The blocks are not contiguous

Uploaded by

Aamir Chohan
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/ 35

Memory

Management
Chapter 3 - Principles of Data Structures using C by Vinu V Das
Contents
1D and 2D
What is Arrays Single and
Memory DMA Multiple Block
Allocation.

Static Reallocation
Memory in C.
Allocation

Dynamic
Memory De-allocation
Allocation Recap of
in C.
C&
Pointers

Instructor: Aatif Shahbaz 2


Lecture 6
What is Memory. Static Memory Allocation. Dynamic Memory Allocation. Recap of C & Pointers
What is Memory
 A memory is made up of a large number of cells, where each cell is capable of storing one bit.
• The cells may be organized as a set of addressable words, each word storing a sequence of bits.
Such as byte, word, double word etc..

Why memory needed ?


 Memory is required in a computer to store programs (or information or data).
 Data used by the variables in a program is also loaded into memory for fast access.
• Memory management is to handle request and release of storage in most effective manner.
• While designing a program the programmer should concentrate on, how to allocate memory when
it is required and how to de-allocate once its use is over.

 There are two types of memory allocations in C, C++:


Static :
• It is done at Compile time.
Dynamic :
• It is done at Run time.
Instructor: Aatif Shahbaz 4
Static Memory Allocation
 In static or compile time memory allocations, the required memory is allocated to the variables at the
beginning of the program.
 The memory to be allocated is fixed and is determined by compiler at the compile time itself.

Example :

• int i, j ; // 4 bytes - Two bytes per integer variables in C

 When this statement is compiled, two bytes for each variable „i‟ and „j‟ will be allocated.

• float A[5], f; // 24 bytes - Four bytes per floating point variables in C

 This statement will allocate 20 bytes to the array A (5 elements of floating point type, i.e., 5 × 4) and
four bytes for the variable „f ‟.

 But static memory allocation has some drawbacks.

Instructor: Aatif Shahbaz 5


Drawbacks
Access Problem:
Read :
• If you try to read 15 elements, of an array whose size is declared as 10, then first 10 values and
other five consecutive unknown random memory values will be read.

Write :
• If you try to assign values to 15 elements of an array whose size is declared as 10, then first 10
elements can be assigned and the other 5 elements cannot be assigned/accessed.

Inefficient Utilization :
• Another problem with static memory allocation is that if you store less number of elements than
the number of elements for which you have declared memory, and then the rest of the memory
will be wasted. That is the unused memory cells are not made available to other applications (or
process which is running parallel to the program) and its status is set as allocated and not free. This
leads to the inefficient use of memory.

Instructor: Aatif Shahbaz 6


Dynamic Memory Allocation
 The dynamic or run time memory allocation helps us to overcome problems with static allocation.
 It makes efficient use of memory by allocating the required amount of memory whenever is needed.
 In most of the real time problems, we cannot predict the memory requirements.
 Dynamic memory allocation does the job at run time.

 C language provides following dynamic allocation and de-allocation functions in <stdlib.h> library :

Allocation :
• malloc( )
• calloc( )
• realloc( )

De-allocation :
• free( )

Instructor: Aatif Shahbaz 7


Recap of C Language
C++ Language Elements
#include <iostream> // cout, cin declaration

std::cout << “Enter the distance in miles”;


std::cin >> miles ;

std::cout << “That equals” << kms << “kilometers. \n” ;

Instructor: Aatif Shahbaz 9


C Language Elements

Instructor: Aatif Shahbaz 10


Difference between C++ and C Syntax
C++ Language Elements C Language Elements

#include <iostream> #include <stdio.h>


using namespace std;
cout << “Hello C++” ; printf(“Hello C”);
cout << “distance is” << var; printf(“distance is %f”, var);
cin >> var ; scanf(“%f”, &var);

#include <cmath> #include <math.h>

cout << string ; puts(string);

getline(cin, string); gets(string);

Instructor: Aatif Shahbaz 11


Pointers
 A special variable that stores the address of a data item.

Example :

• int m = 25;
• int * itemp; // a pointer to an integer or integer type pointer

 The above statements allocate storage for an int variable m and a pointer variable itemp.

• itemp = &m; // Store address of m in pointer itemp

 The above statement stores the memory address of m in pointer itemp .

 It applies the unary address of operator & to m to get its address, which is then stored in itemp .
 This is the same & operator that appears in scanf( ) functions in C language.

Instructor: Aatif Shahbaz 12


Reference with Pointers
 Accessing the contents of a memory cell through a pointer variable that stores its address.

 If you write printf(“%u” , itemp)


• then 1024 will show as output.

 If you write printf(“%d” , *itemp)


• then 25 will show as output.

 Notice the difference between the reference and dereference operators:


• & is the reference operator and can be read as "address of"
• * is the dereference operator and can be read as "value pointed by"

Instructor: Aatif Shahbaz 13


Pointers - Example
void main (void)
{ int firstvalue = 15, secondvalue = 5, thirdvalue = 35;
int * p1, *p2, *p3;

p1 = &firstvalue;
p2 = &secondvalue;
p3 = &thirdvalue;

*p1 = 10;
*p2 = *p3;
p1 = p3;
*p1 = *p2;
p2 = p3;
*p2 = 50;
p3 = &firstvalue;
*p3 = *p1;

printf(“firstvalue = %d, secondvalue = %d, thirdvalue = %d”, firstvalue, secondvalue, thirdvalue); }

Instructor: Aatif Shahbaz 14


Pointer to Pointer
 A pointer to a pointer is a form of multiple indirection, or a chain of pointers.
• When we define a pointer to a pointer, the first pointer contains the address of the second pointer,
which points to the location that contains the actual value as shown below.

int main (void)


{
int var = 3000
int *ptr;
int **pptr;
ptr = &var; // take the address of var
pptr = &ptr; // take the address of ptr using address of operator &

printf("Value of var = %d\n", var );


printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr); return 0; }
Instructor: Aatif Shahbaz 15
Assignment 3
Write a program for Factorial example in C
 Ask user about a number, calculate its factorial and display result.

Write a program for Prime number example in C


 Ask user about a number and check if it is prime or not, display result for both cases.
Lecture 7
Single and Multiple Block Allocation. Reallocation in C. De-allocation in C. 1D and 2D Arrays DMA
Dynamic Memory Allocation
Allocating Single Block
 The malloc( ) function is used to allocate a block of memory in bytes.
 It returns a pointer of any specified data type after allocating a block of memory of specified size.
 It is of the form
• ptr = (any_type *) malloc (block_size)

 „ptr‟ is a pointer of any type, „any_type‟ byte size is the allocated area of memory block.

Example :
• ptr = (int *) malloc (10 * sizeof (int));

 On execution of this statement, 10 times memory space equivalent to size of an „int‟ byte is allocated
and the address of the first byte is assigned to the pointer variable „ptr‟ of type „int‟.

• Remember the malloc( ) function allocates a block of contiguous bytes. The allocation can fail if the
space in the heap is not sufficient to satisfy the request. If it fails, it returns a NULL pointer. So it is
always better to check whether the memory allocation is successful or not before using it.
• The memory allocated using malloc( ) function contains garbage values by default.
Instructor: Aatif Shahbaz 19
Malloc( ) - Example
 A program to find the sum of N elements using dynamic memory allocation

#include<stdio.h>
#include<conio.h>

void main(void)
{ int i, j, n, sum =0, *ptr;

printf("\nEnter the number of the element(s) to be added = ");


scanf("%d",&n);

ptr=(int*)malloc(n*sizeof(int)); // Allocating memory space for n integers of int type to *ptr

if(ptr == NULL) // Checking whether the memory is allocated successfully


printf("\n\nMemory allocation is failed") ;

Instructor: Aatif Shahbaz 20


Malloc( ) - Example
else
{ for(i=0 ; i < n ; i++) //Reading the elements to the ptr
{
printf("Enter the %d element = ", i+1);
scanf("%d", ptr+i ); // ptr+i = &ptr[ i ] - In other words array is constant pointer
}

for(j=0 ; j< n ; j++) //Finding the sum of n elements


sum=sum+ (*(ptr+j)); // *(ptr+i) = ptr[ i ] - In other words pointer is variable array

printf("\n\nThe SUM of no(s) is = %d", sum);


}
getch( );
}

Instructor: Aatif Shahbaz 21


Array- Example
 Trying to do same example with array using run time memory allocation of N elements.

#include<stdio.h>
#include<conio.h>

void main(void)
{ int i, j, n, sum =0;

printf("\nEnter the number of the element(s) to be added = ");


scanf("%d",&n); //Enter the number of elements

int arr[ n ] ; //Trying to allocate memory dynamically to array

for(i=0 ; i < n ; i++) //Reading the elements to the ptr


{ printf("Enter the %d element = ", i+1);
scanf("%d", arr[ i ] ) ; }
Instructor: Aatif Shahbaz 22
Array - Example
for(j=0 ; j< n ; j++) //Finding the sum of n elements
sum=sum+ (arr[ j ]);

printf("\n\nThe SUM of no(s) is = %d", sum);

getch( );
}

Hypothesis :
 The program generate a compilation error that “an array subscript must be a constant value”.
 Array is a static data structure according to ISO C, C++ standards.
• Its memory allocation must be done at compile time.
• Run time allocation is not compatible with arrays.
Solution:
 Use malloc( ) if dynamic memory allocation is required.

Instructor: Aatif Shahbaz 23


Allocating Multiple Block
 While malloc( ) function allocates a single block of memory space, calloc( ) function allocates multiple
blocks of memory, each of the same size, and then sets all bytes to zero.

 The calloc( ) function works exactly similar to malloc( ) function except for the fact that it needs two
arguments as against one argument required by malloc( ) function.

 The general form of calloc( ) function is


• ptr = (any_type*) calloc(n, sizeof (block_size));
• ptr = (any_type*) malloc(n* (sizeof (block_size)));

 The above statements allocates contiguous space for „n‟ blocks, each of size of block_size bytes.

Example:
• ptr = (int *) calloc(25,sizeof (float));

 Here, the size of data type in byte for which allocation is to be made (4 bytes for a floating point
numbers) is specified and 25 specifies the number of elements for which allocation is to be made.
Instructor: Aatif Shahbaz 24
Calloc( ) - Example
 A program to find the sum of N elements using dynamic memory allocation

#include<stdio.h>
#include<conio.h>

void main(void)
{ int i, j, n, sum =0, *ptr;

printf("\nEnter the number of the element(s) to be added = ");


scanf("%d",&n);

ptr=(int*)calloc(n, sizeof(int)); // Allocating memory space for n integers of int type to *ptr

if(ptr == NULL) // Checking whether the memory is allocated successfully


printf("\n\nMemory allocation is failed") ;

Instructor: Aatif Shahbaz 25


Calloc( ) - Example
else
{ for(i=0 ; i < n ; i++) //Reading the elements to the ptr
{
printf("Enter the %d element = ", i+1);
scanf("%d", ptr+i ); // ptr+i = &ptr[ i ] in other words array is constant pointer
}

for(j=0 ; j< n ; j++) //Finding the sum of n elements


sum=sum+ (*(ptr+j)); // *(ptr+i) = ptr[ i ] in other words pointer is variable array

printf("\n\nThe SUM of no(s) is = %d", sum);


}
getch( );
}

Instructor: Aatif Shahbaz 26


Reallocation
 In some situations, the previously allocated memory is insufficient to run the correct application, i.e.,
we want to increase the memory space.
 It is also possible that the memory allocated is much larger than necessary, i.e., we want to reduce
the memory space.
 In both the cases already allocated size of memory block needs to be chanced.
 This can be done by realloc( ) function. This process is called memory reallocation.
 The syntax of this function is
• ptr = realloc(ptr, New_Size)

 Where „ptr‟ is a pointer holding the starting address of the allocated memory block. And New_Size is
the size in bytes that the system is going to reallocate.

 Following example will elaborate the concept of reallocation of memory.


• ptr = (int *) malloc(sizeof (int)); // memory allocation needs to done before trying reallocation
• ptr = (int *) realloc(ptr, sizeof (int)); // memory reallocation when memory has already allocated.

Instructor: Aatif Shahbaz 27


Dynamic Memory De-Allocation
Memory Release
 Dynamic memory allocation allocates block(s) of memory when it is required and de-allocates or
releases when it is not in use.
 It is important and is programmer responsibility to release the memory block for future use when it is
not in use.
 The free( ) function is used to de-allocate the previously allocated memory using malloc( ) or calloc( )
function.
 The syntax of this function is
• free(ptr);

 „ptr‟ is a pointer to a memory block which has already been allocated by malloc() or calloc() functions.
• Trying to release an invalid pointer may create problems and cause system crash.

 The dynamically allocated memory cells are not made available to other applications and its status
remains set to allocated, till free( ) function has been called, to release it.

Instructor: Aatif Shahbaz 29


Free( )- Example
 A program to find the sum of N elements using dynamic memory allocation

#include<stdio.h>
#include<conio.h>

void main(void)
{ int i, j, n, sum =0, *ptr; //Allocate memory space for two-integer pointer variable

printf("\nEnter the number of the element(s) to be added = ");


scanf("%d",&n); //Enter the number of elements

ptr=(int*)malloc(n*sizeof(int)); //Allocating memory space for n integers of int type to *ptr

if(ptr == NULL) //Checking whether the memory is allocated successfully


printf("\n\nMemory allocation is failed") ;

Instructor: Aatif Shahbaz 30


Free( ) - Example
else
{ for(i=0 ; i < n ; i++) //Reading the elements to the ptr
{
printf("Enter the %d element = ", i+1);
scanf("%d", ptr+i ); // ptr+i = &ptr[ i ] in other words array is constant pointer
}

for(j=0 ; j< n ; j++) //Finding the sum of n elements


sum=sum+ (*(ptr+j)); // *(ptr+i) = ptr[ i ] in other words pointer is variable array

printf("\n\nThe SUM of no(s) is = %d", sum);


}
free(ptr) ; // Releasing allocated memory
getch( ); }

Instructor: Aatif Shahbaz 31


2D Dynamic Memory (De)Allocation
Allocation :
int** x; [0] [1] [2] [3] [4] [5]

x = (int**)calloc(dimension1 , sizeof(int*)); x
for (int i = 0; i < dimension1 ; i++)
{
[0]
x[ i ] = (int*)calloc(dimension2 , sizeof(int));
} [1]

[2]
De-allocation :
[3]
for (int i = 0; i < dimension1 ; i++)
{ [4]
free(x[ i ]); [5]
}
free(x); Also called DYNAMIC ARRAY
Instructor: Aatif Shahbaz 32
Dynamic Array

ptr[ i ][ j ] = *(ptr[ i ] + j) = *(*(ptr + i) + j)

Instructor: Aatif Shahbaz 33


Difference between C and C++ Syntax
C Language Elements C++ Language Elements
#include <stdio.h> #include <iostream>
using namespace std;
printf(“Hello C”); cout << “Hello C++” ;
printf(“distance is %f”, var); cout << “distance is” << var;
scanf(“%f”, &var); cin >> var ;

Dynamic Memory Management

malloc( ), calloc( ) new

realloc( ) -

free( ) delete

Instructor: Aatif Shahbaz 34


Assignment 4
Do stepwise refinement step1, step2 and step3 for given example
 Matrix multiplication of order N x N (Suppose N= 3 for step3)

Re-write complete program for given example in C using DMA


 Matrix multiplication of order N x N

You might also like