Skip to main content

Dynamic Memory Allocation in C programming


             The process of allocating and freeing memory at run time is known as Dynamic Memory Allocation. This conserves the memory required by the program and returns this valuable resource to the system once the use of reserved space is utilized.
         Since an array name is actually a pointer to the first element within the array, it is possible to define the array as a pointer variable rather than as a conventional array. While defining conventional array, system reserves fixed block of memory at the beginning of program execution which is inefficient but this does not occur if the array is represented in terms of a pointer variable. The use of a pointer variable to represent an array requires some type of initial memory assignment before the array elements are processed. This is known as DMA.
                There are four library functions malloc(), calloc(), free() and realloc() for memory management. These functions are defined within header file stdlib.h and alloc.h .They are described as follow.


 i) malloc()
       It allocates requested size of bytes and returns a pointer to the first byte of the allocated space. Its syntax is as
      ptr=(data_type*) malloc(size_of_block);
   Here, ptr is a pointer of type data_type. The malloc() returns a pointer to an area of memory with size size_of_block.
  An example:
              x=(int*) malloc(100*sizeof(int));
A memory space equivalent to “100 times the size of a integer (i.e. 100*2bytes =200 bytes ” bytes is reserved and the address of the first byte of the memory allocated  is assigned to the pointer x of type int.

ii) calloc()
        It allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory. The function calloc()  allocates multiple blocks of storage, each of the same size and then sets all bytes to zero. Thus, it is normally used for requesting memory space at run time for storing derived data types such as arrays and structure. Its syntax is
         ptr=(data_type*) calloc(no_of_blocks, size_of_each_block);
An example:
              x=(int*) calloc(5, 10*sizeof(int));
The above statement allocates contiguous space for 5 blocks, each of size 20 bytes i.e. we can store 5 arrays, each of 10 elements of integer types.

iii) free();
    This built-in function frees previously allocated space. The memory dynamically allocated is not returned to the system until the programmer returns the memory explicitly. This can be done using free() function. Thus, this function is used to release the space when it is not required. Its syntax is
      free(ptr);
Here, ptr is a pointer to a memory block which has already been created by malloc() or calloc() function.

iv) realloc();

      This function is used to modify the size of previously allocated space. Sometimes, the previously allocated memory is not sufficient and we need additional space and sometime the allocated memory is much larger than necessary. In both situations, we can change the memory size already allocated with the help of function realloc(). Its syntax is as
    If the original allocation id done by the statement
             ptr=malloc(size);
  then, reallocation of space may be done by the statement
              ptr=realloc(ptr,newsize);
    This function allocates a new memory space of size newsize to the pointer variable ptr and returns a pointer to the first byte of the new memory block.

An example related to realloc()
        
   #include<stdlib.h>
void main()
 {
 char *name;
 name=(char*)malloc(10);
 strcpy(name,"Ram Datta");
 printf("\n Name=%s",name);
 name=(char*)realloc(name,20);
 strcpy(name,"Bhatta Ram Datta abc ");
 printf("\n Name=%s",name);
 getch();
 }

Another Example: 
                   Write a program to read number of students and their marks and display the average of entered marks. Use array as pointer instead of conventional array to represent marks of different students.       
#include<stdlib.h>
     void main( )
           {
            int s,i;
            float *p,sum=0,avg;
            clrscr();
            printf("\nHow many students are there?\n");
            scanf("%d",&s);
            printf("\n Enter marks of each students\n");
            p=(float*)malloc(s*sizeof(float));
              for(i=0;i<s;i++)
                {
                  scanf("%f",p+i);
                  sum+=*(p+i);
                }
              avg=sum/s;
            printf("\n The average marks is\t%f",avg);
            free(p);
            getch();
       }

Comments

Popular posts from this blog

Difference between Binary mode and Text Mode in C programming

There are mainly three difference between binary and text mode. They are as follow.               i.       In text mode, a special character EOF whose ASCII value is 26 is inserted after the last character in the file to mark the end of file. But, there is no such special character present in the binary mode. The binary mode files keep track of the end of file from the number of characters present in the directory entry of the file.             ii.       In text mode of file, text and numbers are stored as one character per byte. For example, the number 1234 occupies two bytes in memory but it occupies 4 bytes (one byte per character) in the file. But, in binary mode, the number occupies the number of bytes as it occupies in the memory. Thus,  the above number occupies two bytes in file also in the case o...

CPU (Central Processing Unit)

PGA reffered as pin grid array in which pins of CPU are lined up in a straight format. SPGA referred as staggered pin grid array. in which pins of CPU are arranged staggered format. LGA reffered to as Land Grid Array in which pins are available within inside the socket but not in the CPU in other words in line grid array, in CPU ther are no pinsbut insteadpins areattached with in a socket which contact with with the CPU. for e.g. LGA775 socket(no pins on cpu) has better cooling system. better contact and better locking(climbing). LGA1155: Letest generation I socket, also reffered as sandy bridge, Turbo boost overclocking. More resent than LGA 1156 socket. LGA1156: ability to north bridge Doul channel DDR3 optional integreted graphics PCI express LGA1366: hi end core i series socket integreted tiple channal memmory controller external control bridge(HUB) Upgrading CPU: need to check its core suppert check multiprocessor supports or not check on the ...

Types of Functions in C Programming

C program has two types of functions: 1. Library Functions 2. User defined functions Library Functions: These are the functions which are already written, compiled and placed in C Library and they are not required to be written by a programmer. The function’s name, its return type, their argument number and types have been already defined. We can use these functions as required. For example: printf(), scanf(), sqrt(), getch(), etc. User defined Functions: These are the functions which are defined by user at the time of writing a program. The user has choice to choose its name, return type, arguments and their types. The job of each user defined function is as defined by the user. A complex C program can be divided into a number of user defined functions. For example: #inlcude<stdio.h> double convert (int) ; /* function proto type */ main() { int c ; /* double d ; */ printf (“Enter temperature in Celsius: ”) ; scanf (“%d”, &c) ; /* d =...