Exforsys.com
 
Home Tutorials C Language
 

C Programming - Dynamic Memory allocation

 

C Programming - Dynamic Memory allocation

In this tutorial you will learn about C Programming - Dynamic Memory Allocation, Dynamic memory allocation. Memory allocations process, Allocating a block of memory, Allocating multiple blocks of memory, Releasing the used space and To alter the size of allocated memory.

 

Sponsored Links

 

In programming we may come across situations where we may have to deal with data, which is dynamic in nature. The number of data items may change during the executions of a program. The number of customers in a queue can increase or decrease during the process at any time. When the list grows we need to allocate more memory space to accommodate additional data items. Such situations can be handled move easily by using dynamic techniques. Dynamic data items at run time, thus optimizing file usage of storage space.


Dynamic memory allocation:

The process of allocating memory at run time is known as dynamic memory allocation. Although c does not inherently have this facility there are four library routines which allow this function.


Many languages permit a programmer to specify an array size at run time. Such languages have the ability to calculate and assign during executions, the memory space required by the variables in the program. But c inherently does not have this facility but supports with memory management functions, which can be used to allocate and free memory during the program execution. The following functions are used in c for purpose of memory management.


Function


Task


malloc


Allocates memory requests size of bytes and returns a pointer to the Ist byte of allocated space


calloc


Allocates space for an array of elements initializes them to zero and returns a pointer to the memory


free


Frees previously allocated space


realloc


Modifies the size of previously allocated space.



Memory allocations process:

According to the conceptual view the program instructions and global and static variable in a permanent storage area and local area variables are stored in stacks. The memory space that is located between these two regions in available for dynamic allocation during the execution of the program. The free memory region is called the heap. The size of heap keeps changing when program is executed due to creation and death of variables that are local for functions and blocks. Therefore it is possible to encounter memory overflow during dynamic allocation process. In such situations, the memory allocation functions mentioned above will return a null pointer.


Allocating a block of memory:

A block mf memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. It takes the following form:

ptr=(cast-type*)malloc(byte-size);


ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory with size byte-size.


Example:


x=(int*)malloc(100*sizeof(int));


On successful execution of this statement a memory equivalent to 100 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int


Allocating multiple blocks of memory:

Calloc is another memory allocation function that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero. The general form of calloc is:

ptr=(cast-type*) calloc(n,elem-size);


The above statement allocates contiguous space for n blocks each size of elements size bytes. All bytes 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:

Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required. The release of storage space becomes important when the storage is limited. When we no longer need the data we stored in a block of memory and we do not intend to use that block for storing any other information, we may release that block of memory for future use, using the free function.


free(ptr);


ptr is a pointer that has been created by using malloc or calloc.


To alter the size of allocated memory:

The memory allocated by using calloc or malloc might be insufficient or excess sometimes in both the situations we can change the memory size already allocated with the help of the function realloc. This process is called reallocation of memory. The general statement of reallocation of memory is :


ptr=realloc(ptr,newsize);

This function allocates new memory space of size newsize to the pointer variable ptr ans returns a pointer to the first byte of the memory block. The allocated new block may be or may not be at the same region.


/*Example program for reallocation*/
#include< stdio.h >
#include< stdlib.h >
define NULL 0
main()
{
char *buffer;
/*Allocating memory*/
if((buffer=(char *) malloc(10))==NULL)
{
printf(“Malloc failed\n”);
exit(1);
}
printf(“Buffer of size %d created \n,_msize(buffer));
strcpy(buffer,”Bangalore”);
printf(“\nBuffer contains:%s\n”,buffer);
/*Reallocation*/
if((buffer=(char *)realloc(buffer,15))==NULL)
{
printf(“Reallocation failed\n”);
exit(1);
}
printf(“\nBuffer size modified.\n”);
printf(“\nBuffer still contains: %s\n”,buffer);
strcpy(buffer,”Mysore”);
printf(“\nBuffer now contains:%s\n”,buffer);
/*freeing memory*/
free(buffer);
}






 

 

Comments


parijat dutta said:

  a very good conceptual tutorial......shows the jist of the entire concept of dynamic memory allocation....good for understandin an developin further concepts

KEEP IT UP
June 18, 2007, 10:45 pm

sohan said:

  i just cant believe that i got an idea of memory allocation like this.it gave me a entire concept of allocation.....GOOD JOB
October 19, 2007, 10:30 pm

vijay thapa said:

  it give me a very good reason to get a on my assignment
October 24, 2007, 5:56 am

kajal jaiswal said:

  its helpful in my assignment
October 27, 2007, 3:55 am

Anand Naik said:

  Hi this material is amazing.. It helped me a lot in my project and cleared many of my confusions. I am very thankful to the author. thanks
March 4, 2008, 12:58 am

srikar sarma said:

  ya, nice .its a great thing to explain.kajal point is correct
April 30, 2008, 11:39 am

avinash vibrn said said:

  hi this material is very fruitful for me.
June 3, 2008, 8:18 am

nishana said:

  Good Material.
August 27, 2008, 3:58 am

Sangeetha Kathiresan said:

  Useful Stuff
September 16, 2008, 2:32 am

varun vyas said:

  gift for me as i am a begginer in c and it boosted my cofidence (i know not how but it is so)
September 19, 2008, 9:32 am

grandjonkar said:

  how can i known the blocks allocated in memory before write the file
November 6, 2008, 8:49 am

SUKANTA SAHA said:

  Unbelievable I got a marvelous idea of memory allocation
December 13, 2008, 6:56 am

manju panusa said:

  it is very helpul
January 3, 2009, 9:07 am

kinnu said:

  this material is really good
January 7, 2009, 3:41 am

haritha said:

  material is too good.i have never found material like this.
January 22, 2009, 4:50 am

Angan, New Delhi, India said:

  Wonderful explanation Keep it up. I am new to dynamic memory allocation but got an idea what this substance is.
January 24, 2009, 1:03 am

karan said:

  i wanna learn c n c++ programming thoroughly....
January 26, 2009, 3:19 am

1 said:

  Excellent
January 29, 2009, 10:41 pm

tinhnguyen said:

  ptr=(cast-type*) calloc(n,elem-size);
free(ptr);

How do we can check memory of pointer released after we used command free(ptr)?
Please explain clear for me
April 7, 2009, 3:07 am

salma said:

  Please explain one program using dynamic memory allocation.
June 5, 2009, 6:08 am

haya said:

  Is there any provision to insert a cell dynamically in a dynamically created array.
June 5, 2009, 8:31 am

Ajay Kumar said:

  hey can i design any search engine using c-language,if yes then please guide me
December 26, 2009, 6:52 am

rajalingam.s said:

  What is _msize in this program? Why you are using that?
January 11, 2010, 3:48 am

prabhu.m said:

  struct node {
intm;
struct node*next;
}
x,y,z,*p;
x.m=10;
y.m=20;
z.m=30;
x.next=&y;
y.next=&z;
z.next=NULL;
p=x.next;
while(p=NULL)
{
printf{("%dn",p->m)intm;
p=p->next;
}
}

Dear sir,
please send the output of this dynamic memory allocation and linked lists programm. please sir send immidiatly i want urgent for my project submitting purpose.

MY MAIL ID: prabhu20201989rediffmail.com

and rameshprabhu2010gmail.com
March 25, 2010, 5:27 am

madhan said:

  Was easy to understand :) TY
May 28, 2010, 10:00 pm

P.Parthiban said:

  Before starting to read this page, i've no idea abt memory allocation.
but now i feel good. it will help me to proceed further. Thank u.
June 5, 2010, 12:59 am

shilpy said:

  it really works in understanding the concepts...... for any beginer
June 21, 2010, 2:23 am

nidhi said:

  it really works......... thanks alot
July 27, 2010, 8:04 pm

Jay said:

  Very Useful...Crystal clears the concept
July 28, 2010, 5:36 am

prosen said:

  main()
{
char *ptr;
scanf("%s",ptr);
printf("%s",ptr);
}
this will also take the value at run time...so is this a dynamic string ? if yes then why we use malloc or calloc
July 31, 2010, 1:40 pm

saru said:

  int i=10 where it stores?
August 10, 2010, 3:51 am

pradeep said:

  In integer 1st bit store address and second bit store the value of integer, which length is 0 to 255 in bits, if we want to store integer 32000, then is it possible to store in one bit address , if then how can you plx give me brief description.
August 10, 2010, 12:05 pm

MARUATA said:

  There'r some mistake in the program. So I just change a bit.


/*Example program for reallocation*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <stdio.h>
#include <conio.h>
#define NULL 0

int main()
{
char *buffer;
/*Allocating memory*/
if((buffer=(char *) malloc(10))==NULL)
{
printf("Malloc failedn");
exit(1);
}
printf("Buffer of size %d created n",_msize(buffer));
strcpy(buffer,"Bangalore");
printf("nBuffer contains:%sn",buffer);
/*Reallocation*/
if((buffer=(char *)realloc(buffer,15))==NULL)
{
printf("Reallocation failedn");
exit(1);
}
printf("nBuffer size modified.n");
printf("nBuffer still contains: %sn",buffer);
strcpy(buffer,"Mysore");
printf("nBuffer now contains:%sn",buffer);
/*freeing memory*/
free(buffer);
getch();
return 0;
}
August 11, 2010, 9:56 am

diksha kulshreshtha said:

  nice,very nice......
August 12, 2010, 11:44 pm

shweta.tenginkai said:

  It was fabulous understanding this concept based article
August 19, 2010, 2:47 am

Archana Allishe said:

  Its really very nice material for understanding dynamic memory allocation.
August 31, 2010, 5:02 am

Post Your Comment:

Members Please Login
Your Name:*
e-mail ID:(required for notification)*
Image Verification: 
 
 Subscribe    

Sponsored Links

 

 
 


Get Daily Updates via Subscribe to Exforsys Free Training via email


Get Latest Free Training Updates delivered directly to your Inbox...

Enter your email address:


 

Subscribe to Exforsys Free Training via RSS
 

 
 
Partners -  Privacy and Legal Policy -  Site News -  Contact   Sitemap  

Copyright © 2000 - 2010 exforsys.com. All Rights Reserved

Page copy protected against web site content infringement by Copyscape