Dynamic Memory Allocation


*          Instead of allocating memory during compile time, we can allocate memory during the runtime of program.

*          Allocating memory during the execution time, is known as Dynamic memory allocation.

            We have some disadvantages over static memory allocation. Consider the following case of allocating 100 bytes for 50 integer array        elements.

            Suppose if we input only 20 elements, then 60 bytes of memory are getting wasted. Otherwise, if we want to input 55 elements, we cannot extend the memory.

            For overcoming this, DMA provides three functions coming under
            alloc.h header file.


            1. malloc() : memory allocation

            syntax :  Pointer-Var=malloc(bytes);

            malloc function allocates the given number of bytes and it returns the address of first byte allocated.

            2. calloc() : clear memory allocation

            syntax : calloc(n,b);

            n - number of Blocks
            b – size of each Block

            calloc function allocates the memory needed for storing given number of elements and clears the garbage values of allocated memory.

            3. free() : free memory

            syntax : free(address);

            Free function de-allocates the memory block to the given address.

            4. sizeof(var|expr) :
            gives the size of the given expr or variable size = number of bytes    needed to store var or expr.

            5. realloc():-
                        This function is used to Increase or Decrease the sizeof already memory allocated.
            Syntax:
                        realloc(old-ptr,new-size);

No comments: