14-Dynamic Memory Allocation

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 36

DYNAMIC MEMORY

ALLOCATION
Disadvantages of ARRAYS

MEMORY ALLOCATION OF ARRAY IS STATIC:


Less resource utilization.
For example:
If the maximum elements declared is 30 for an array,
say int test[30], but the user manipulates with only 10
elements, then the space for 20 elements is wasted.

DIFFERENT DATA TYPES COULD NOT BE STORED


IN AN ARRAY
 The use of pointer variable instead of arrays, helps in
allocation of memory at RUN TIME, thus memory can be
allocated or freed anywhere, anytime during the program
execution.

• This is known as DYNAMIC MEMORY ALLOCATION


STATIC vs DYNAMIC

• The allocation of memory for the specific fixed purposes


of a program in a predetermined fashion controlled by
the compiler is said to be static memory allocation.

• The allocation of memory (and possibly its


later de allocation) during the run time of a
program and under the control of the program
is said to be dynamic memory allocation.
Memory Allocation
 In DYNAMIC memory allocation, the memory is allocated to the
variables in the HEAP region.

 The size of HEAP keeps on changing due to creation and death


of variables.

 Thus it is possible to encounter “memory overflow” during


dynamic memory allocation process.

 In such situation memory allocation library function returns a


NULL pointer when they fail to locate enough memory
requested.
Memory Allocation Functions

The following are four memory management


functions defined in library of C that can be used for
allocation and freeing of memory when ever
required.
» malloc
» calloc
» free
» realloc
All the above four functions are defined in library file
<alloc.h>.
malloc ( )
 malloc : It is a predefined library function that allocates
requested size of bytes and returns a pointer to the first byte of
the allocated space.

 Pointer returned is of type void that has to be type cast to the


type of memory block created (int, char, float, double).

 General syntax:
ptr = (cast –type * ) malloc( byte-size ) ;
where ptr is pointer of any data type.
malloc returns a pointer to an area of
memory with size byte-size.
Example 1

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

Returns the size of


integer
Type cast Number of elements in the
array ptr is pointing to.

Allocate 200 bytes i.e declare an array of 100 integers


with pointer ptr pointing to the first element of the
array
Alternative

int * ptr ;
printf ( “\n Enter the number of elements in the array “);
scanf(“%d”, &n);
ptr = ( int *) malloc ( n x sizeof ( int ) ) ;

int * ptr ;
ptr = ( int *) malloc ( 200 ) ;
Example 2
char * cptr ;
cptr = ( char * ) malloc ( 10 ) ;

This will allocate 10 bytes of memory space for the pointer cptr of type char.

cptr pointer holding the address of the first


byte of the array of 10 elements

? ? ? ? ? ? ? ? ? ?
10 bytes of space
Important

 The storage space allocated dynamically has NO name


and therefore its contents are accessed ONLY through a
pointer.

 malloc allocates blocks of contiguous memory locations.

 If allocation fails due to in sufficient space on HEAP, it


returns NULL pointer. Thus when ever we allocate
memory it should be checked whether the memory has
assigned successfully or not.
Exercise

 Write a program to create an array of integers.Size


of the array that is number of elements in the array
will be specified interactively by the user at RUN
TIME.
SOLUTION
#include<alloc.h>
int main( ) {
int *p, *table, size ;
printf(“\n Enter the size of array “);
scanf(“%d”, &size);
/* memory allocation */
if( table = (int * ) malloc ( size * (sizeof (int) ) ) == NULL )
{ printf(“\n NO space available “);
exit(1);
}
printf(“\n Address of first byte is %p”,table);
Visualization

If size = 10 => 20 bytes will be allocated.

Integer pointer * table pointing to first


element of array
SOLUTION cont’d: Reading values in the array

// reading values in array


printf(“\n Input table value “);
for( p= table; p<table + size ; p++)
scanf(“%d”, p ); // no ampersand as p is pointer

// printing values of array in reverse order


for( p = table+size – 1 ; p >= table ; p-- )
printf(“%d”, *p);
Visualization

table for( p= table; p<table + size ; p++)


scanf(“%d”, p );

pointerpointer
*p *p pointer * p
Printing values in reverse order

for( p = table+size – 1 ; p >= table ; p-- )


* table
printf(“ %d”, *p);

pointer * p pointer
pointer
*p *p
OUTPUT
What is the size of array ? 5
Address of first byte : 077FA

Input values: 11 12 13 14 15

OUTPUT values in reverse order


15
14
13
12
11
calloc ( )
 calloc ( ): It also allocates the requested number of
bytes, but the difference is that it takes two parameters:
» N : number of elements
» Element_size: size of element in bytes

 Also when the memory is allocated, all the elements are assigned a initial value of zero.
 This is not provided by function malloc ( )

General syntax:
ptr = (cast _type * ) calloc (n, element_size);
 The above statement allocates contiguous space
for n elements, each of size element_size.

 All elements are initialized to zero and a pointer to


the first byte of the allocated region is returned.

 If there is not enough space, a NULL pointer is


returned.
Releasing the Used Space
 In case of Dynamic RUN Time allocation, it is the
responsibility of the programmer to release the
memory space when it is not required by the
program.

 When a block of data in memory is no longer needed


by the program, it should be released as memory is a
factor in executing complex programs.
free ( )

 To release the memory currently allocated to a


pointer using DYNAMIC ALLOCATION use the
following function:
free ( ptr );
where ptr is a pointer to a memory block which
has already been created using either malloc or
calloc .
Altering the size of memory block

 REALLOCATION function (realloc)


Example

 If the original allocation was done by the


statement:
ptr = (cast_type * ) malloc ( size ) ;

 Then REALLOCATION of space is done by :


ptr = (cast_type * )realloc ( ptr, NEW_SIZE );
How It works ? ? ?
 This function allocates a new memory space of size
NEW_SIZE to the pointer variable ptr and returns a
pointer to the first byte of the new memory block.

 The NEW_SIZE may be larger or smaller than the


original size.

 The new block of memory MAY or MAY NOT begin


at the same place as the previously allocated
memory block.
 The function guarantees that the old data will
remain intact, if it run successfully.

 If the function is unsuccessful in locating additional


space, it returns a NULL pointer and the original
block is FREED [ lost ] .
Memory allocation function

If memory allocation fails, these functions return a


NULL pointer.
Since these functions return a pointer to void, when
allocating memory use conversion:
pi = (int*)malloc(5*sizeof(int)); /* or */
pi = (int*)calloc(5, sizeof(int));
pi = (int*)realloc(pi, 10*sizeof(int));
Exercise

 Write a program to store a character string in a


block of memory space created by malloc and then
modify the same to store a larger string.
SOLUTION
int main(void)
{
char * buffer ;
/* allocating memory */
if( (buffer = (char *) malloc (10 ))== NULL )
{ printf(“ NOT ENOUGH SPACE “ );
exit (1 ); }
strcpy(buffer, “ NOIDA “ );
/* reallocating space */
if ( (buffer = (char *) realloc( buffer, 15 ) ) == NULL )
{ printf(“ REALLOCATION FAILS “);
exit (1 );
}
printf(“ Buffer contains : %s”, buffer );

strcpy( buffer, “ JIIT,Noida”);

Printf(“ Buffer contains : %s “, buffer );

/* freeing the memory */


free ( buffer );
}
Two dimensional Array

 In the same manner it is also possible to create a


two dimensional array at RUN TIME using malloc
( ) or calloc ( ).

 For creating a two dimensional array, declare a


pointer as follows:
data_type ** pointer ;

example:
int **p;
Example: creating a 2D array of m rows and n columns.
int main()
{ int **ptr;
int m, n;
printf(“\n Enter the number of rows:”);
scanf(“%d”, &m);
printf(“\n Enter the number of columns:”);
scanf(“%d”, &n);
/* creating an array of m pointers */
ptr = (int**) malloc ( m *sizeof(int*));
/* allocating each pointer a row ( 1 D array) */
for (i = 0; i < m; i++)
ptr[i] = (int *)malloc( n * sizeof(int));
int **ptr

ptr[0]
ptr[1]

ptr[2]

ptr[3]

ptr[4]
Check This Out !!!

 Is it possible to create a TWO Dimensional array with m rows, where each row will
have different number of columns ? ? ?

YES ! ! !
Visualization
Advantages

 There are number of reasons for using pointers:

 Pointers are more efficient in handling data tables.


 Pointer reduces the length and complexity of a
given problem.
 Pointer increase the execution speed.
 The use of a pointer array to character strings
results in saving of data storage space in memory.

You might also like