Wednesday 14 July 2010

Dynamic Memory Allocation

The process of allocating memory at runtime is known as dynamic memory allocation. Library routines known as "memory management functions" are used for allocating and freeing memory during execution of a program. These functions are defined in stdlib.h.

Function        Description
malloc()    allocates required size of bytes and returns a void pointer pointing to the first byte of the          allocated space
calloc()     allocates space for an array of elements, initialize them to zero and then return a void pointer to the memory
free()         releases previously allocated memory
realloc()     modify the size of previously allocated space

malloc()

malloc() function is used for allocating block of memory at runtime. This function reserves a block of memory of given size and returns a pointer of type void. This means that we can assign it to any type of pointer using typecasting. If it fails to locate enough space it returns a NULL pointer.

Example:
int *x;
x = (int*)malloc(50 * sizeof(int));    //memory space allocated to variable x
free(x);                    //releases the memory allocated to variable x

calloc():
calloc() is another memory allocation function that is used for allocating memory at runtime. calloc function is normally used for allocating memory to derived data types such as arrays and structures. If it fails to locate enough space it returns a NULL pointer.

Difference Between malloc() and calloc()
malloc()                                                                                  
1. malloc() initializes the allocated memory with garbage values. 
2. Number of argument is 1
Syntax :
(datatype *)malloc(specify the size of bytes);


calloc()
1. calloc() initializes the allocated memory with 0 value.
2. Number of arguments is 2
Syntax :
(data_type *)calloc(blocks , size_of_block);


#include <stdio.h>
#include <alloc.h>
void main()
{
    int n,i,*ptr,sum=0;
    printf("Enter number of elements: \n");
    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 array: ");
    for(i=0;i<n;++i)
    {
        scanf("%d",ptr+i);
        sum+=*(ptr+i);
    }
    printf("Sum=%d",sum);
    free(ptr);

}



You may like the following posts:


No comments:

Post a Comment