Sunday 28 January 2018

Dynamic memory allocation in c

We all know that we have to declare the size of the array before we start to use it. Hence, the array which we declare may be insufficient or more than required to hold data. To solve this issue, you can allocate memory dynamically.
Dynamic memory management refers to manual memory management. This allows you to obtain more memory when required and release it when not necessary.Allocating memory dynamically helps us to store data without initially knowing the size of the data in the time we wrote the program.


It simply refers to performing manual memory management for dynamic memory allocation in the C programming language via group of functions in the C standard library namely malloc,calloc,realloc and free.These functions can be found in the <stdlib.h> header file.



There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming

malloc() :Allocates requested size of bytes and returns a pointer first byte of allocated space

calloc() :Allocates space for an array elements, initializes to zero and then returns a pointer to memory

free() :deallocate the previously allocated space

realloc():Change the size of previously allocated space



Function with Syntax:


Function
Syntax
malloc ()malloc (number *sizeof(int));
calloc ()calloc (number, sizeof(int));
realloc ()realloc (pointer_name, number * sizeof(int));
free ()free (pointer_name);


Allocating memory Dynamically:


1. malloc() :


malloc means memory allocation

Syntax:ptr = (cast-type*) malloc(byte-size)

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

/*This above statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the pointer points to the address of first byte of memory.*/

Let us understand the concept of malloc using simple code:

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

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

    printf("Enter number of elements: ");
    scanf("%d", &n);

    ptr = (int*) malloc(n * sizeof(int));  //memory allocated using malloc
    if(ptr == NULL)                     
    {
        printf("Error! memory not allocated.");
        exit(0);
    }

    printf("Enter elements of  the array: ");
    for(i = 0; i < n; ++i)
    {
        scanf("%d", ptr + i);
        sum += *(ptr + i);
    }

    printf("Sum = %d", sum);
    free(ptr);
    return 0;
}


2.calloc


calloc stand for "contiguous allocation".


The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zer
o.

ptr = (float*) calloc(25, sizeof(float));

This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes.




Let us rewrite the same code using calloc :

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


int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);


ptr = (int*) calloc(num, sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}


printf("Enter elements of array: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}


printf("Sum = %d", sum);
free(ptr);
return 0;
}


3.realloc function

ptr = realloc(ptr, newsize);


realloc function modifies the allocated memory size by malloc and calloc functions to new size.

If enough space doesn’t exist in the memory of current block to extend, a new block is allocated for the full size of reallocation, then copies the existing data to the new block and then frees the old block.



4.free function

free function frees the allocated memory by malloc (), calloc (), realloc () functions.

Let us write the simple code to understand the realloc and free concept better:


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

int main()
{
char *abc;
/* memory is allocated dynamically */
abc = malloc( 20 * sizeof(char) );
if( abc == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( abc,"fresh2refresh.com");
}
printf("Dynamically allocated memory content : " \
"%s\n", abc );
mem_allocation=realloc(mem_allocation,100*sizeof(char));
if( abc == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( abc,"space is extended upto " \
"100 characters");
}
printf("Resized memory : %s\n", abc );
free(abc);
}




Important:


DIFFERENCE BETWEEN STATIC MEMORY ALLOCATION AND DYNAMIC MEMORY ALLOCATION IN C:

Static memory allocationDynamic memory allocation
In static memory allocation, memory is allocated while writing the C program. Actually, user requested memory will be allocated at compile time.In dynamic memory allocation, memory is allocated while executing the program. That means at run time.
Memory size can’t be modified while execution. 
Example: array
Memory size can be modified while execution. 
Example: Linked list

DIFFERENCE BETWEEN MALLOC() AND CALLOC() FUNCTIONS IN C:

malloc()calloc()
It allocates only single block of requested memoryIt allocates multiple blocks of requested memory
int *ptr;ptr = malloc( 20 * sizeof(int) );For the above, 20*4 bytes of memory only allocated in one block. 
Total = 80 bytes
int *ptr;Ptr = calloc( 20, 20 * sizeof(int) );For the above, 20 blocks of memory will be created and each contains 20*4 bytes of memory. 
Total = 1600 bytes
malloc () doesn’t initializes the allocated memory. It contains garbage valuescalloc () initializes the allocated memory to zero
type cast must be done since this function returns void pointer int *ptr;ptr = (int*)malloc(sizeof(int)*20 );Same as malloc () function int *ptr;ptr = (int*)calloc( 20, 20 * sizeof(int) );





No comments:

Post a Comment