Sie sind auf Seite 1von 9

Dynamic memory allocation Dynamic memory management allows you to allocate additional memory space or release

unwanted space at runtime. Lets see how it can be done in this tutorial. Very often we face situations in programming
where the data is dynamic in nature i.e. the number of data items keep changing during execution of the program. For
example, in an employee database, the number of employees continually increase and decrease as and when names are
added or deleted. Accordingly, we need to manage the memory space. his can be done effecti!ely using dynamic data
structures in con"unction with dynamic memory management techni#ues. he ad!antage of dynamic data structures is that
it pro!ides flexibility in adding, deleting or rearranging data items at run time. Dynamic memory management techni#ues
allow us to allocate additional memory space or release unwanted space at run time, thus optimi$ing the use of storage
space. Dynamic memory allocation A good example to illustrate the importance of dynamic memory allocation is arrays.
he number of elements in an array needs to be specified at compile time, but this may not be possible at all times and
e!en if it is possible we usually allocate more space than re#uired. %f the si$e of the array is gi!en wrongly, it may cause
failure of the program or more commonly, wastage of memory space. hus instead of specifying the si$e of the array at
compile time, if we could do it at run time when we are absolutely sure of the re#uired si$e, the program would be more
efficient. he process of allocating memory at run time is known as dynamic memory allocation. Although & does not
inherently ha!e this facility, there are four library routines known as memory management functions that can be used for
allocating and freeing memory during program execution. hey are' malloc' it allocates the re#uested si$e of bytes and
returns a pointer to the first byte of the allocated space. calloc' it allocates space for an array of elements, initiali$es them
to $ero and then returns a pointer to memory. free' frees pre!iously allocated space. realloc' modifies the si$e of pre!iously
allocated space. Allocating memory he malloc function can be used to allocate a block of memory. %t reser!es a block of
memory of specified si$e and returns a pointer of type !oid. his means that we can assign it to any type of pointer. (alloc
allocates a block of contiguous bytes of memory. %t takes the following form' ptr ) *cast+type ,-malloc*byte+si$e-. /ere ptr
is of type cast+type and malloc returns a pointer of cast+type to an area of memory with si$e byte+si$e. For example' x )
*int ,-malloc*011 , si$eof*int--. 2n execution of this statement, a memory space e#ui!alent to 011 times the si$e of int
data type bytes is reser!ed and the address of the first byte of memory allocated is assigned to the pointer x of type int.
3imilarly y ) *char ,-malloc*01-. allocates 01 bytes of space for the pointer y of type char. 4ote' the storage space
allocated dynamically has no name and therefore its contents can be accessed only through a pointer. (alloc can also be
used to allocate space for complex data types such as structures. 5xample' $ ) *struct store ,-malloc*si$eof*struct store--.
where $ is a pointer of type struct store. Lets take a look at a program that illustrates the use of pointers. 6, 7rogram that
uses a table of integers whose si$e will be specified interacti!ely at run time ,6 8include 8define 49LL 1 main*- : int ,p,
,table, si$e. printf*;<n5nter the si$e of the table ';-. scanf*;=d;,>si$e-. if**table)*int ,-malloc*si$e ,
si$eof*int---))49LL- 6, (emory allocation ,6 : printf*;<n4o space a!ailable;-. exit*0-. ? printf*;<n Address of the first
byte is =u<n;,table-. printf*;<n %nput the !alues of the table ';-. for*p)table.p@AAL5B3%C5.7BB- : scanf*;=d;,p-. ?
for*p)table.p@AAL5B3%C5.7BB- ++++++++++++++++++++++++++++++
Linked lists
Lets learn how to release dynamically allocated memory when its no longer re#uired and also how to alter the si$e of
memory space already allocated without altering its contents. his will help us understand more complex structures like
linked lists.

Deleasing used space
Deleasing the space allocated to a !ariable during compile time is done by the system in accordance with the storage class.
%n the case of dynamic run time allocation, releasing the space allocated to !ariables that may not be re#uired becomes our
responsibility when storage is limited. Deleasing a block of memory for future use can be done using the free*- function.
free*ptr-.
ptr is a pointer to a memory block that has already been created by the malloc*- or calloc*- functions. 9se of an in!alid
pointer in the call may create problems and cause system crash.
Altering si$e
Lets say that during the course of a program we reali$e that the memory allocated for a !ariable is not sufficient and we
need additional space for more elements. he !ice !ersa *the memory allocated may be much larger than needed and you
may want to reduce it- may also be true. %n such instances we can change the memory si$e already allocated with the help
of the function realloc*-. his process is called reallocation of memory. For example, if the memory allocation was done by
the statement'
ptr ) malloc*si$e-.
then reallocation may be done by the statement
ptr ) realloc*ptr,newsi$e-.
his function allocates a new memory block of si$e Enewsi$e to the pointer !ariable Eptr and returns a pointer to the new
memory block. he newsi$e may be larger or smaller than the original si$e. 2ne point to be kept in mind is that the new
memory block may not begin at the same place as the old one. %n case it is not able to find additional space in the same
region it will create the same in an entirely new region and mo!e the contents of the old block into the new block. he
function guarantees that the old data will remain intact. %f the function is unsuccessful in allocating additional space, it
returns a 49LL pointer and the original block is freed. hus it becomes !ery important to test the success of the operation
before proceeding further.
Frite a program to store a character string in a block of memory space created by malloc*- and then modify the same to
store a larger string.
6, 7rogram to illustrate the use of realloc*- and free*- function ,6
8include
main*-
:
char ,ptr.
if**ptr ) *char ,-malloc*01--))1- 6, (emory allocation ,6
:
printf*;<nFailure of memory allocation;-.
exit*0-.
?
strcpy*ptr,;Felcome;-.
printf*;<nhe string contained is =s;,ptr-.
if**ptr ) *char ,-realloc*0G--))1- 6, (emory reallocation ,6
:
printf*;<nFailure of memory reallocation;-.
exit*0-.
?
printf*;<nptr still contains the string =s;,ptr-.
strcpy*ptr,;Deallocation;-.
printf*;<nhe string contained is =s;,ptr-.
free*ptr-. 6, Freeing memory ,6
?
4ote' he original contents of the pointer ptr remain the same e!en after the modification of the original si$e.
Linked lists
he word list brings to mind a collection of items organi$ed se#uentially. An array would be an example of a list where
the elements can be accessed with the array index. he index helps us to na!igate to any element in the array. Aut, linked
lists are not about arrays. here each item in the list is a part of a structure that also contains a link to the structure
containing the next item. his kind of list is called a linked list, as it is a list of interconnected nodes.
5ach structure of the list is called a node and consists of two fields one containing the information and the other is the link
field containing the address of the next item in the list. A linked list is, therefore, a collection of structures ordered not by
their physical placement in memory like arrays but by logical links that are stored as part of the data in the structure itself.
he link is in the form of a pointer to another structure of the same type.
Ad!antages of linked lists
A linked list is a dynamic data structure. herefore, the primary ad!antage of linked lists o!er arrays is that linked lists
can increase or decrease in si$e during the execution of a program hence their si$e need not be known at the beginning of
a program and this sa!es precious memory space. %t uses the memory that is "ust needed for the list at any point of time.
Another ad!antage that linked lists ha!e is flexibility. %ts #uite easy to insert or delete items by rearranging the links.
Although there are se!eral ad!antages of using linked lists there are certain drawbacks. using them is a trifle complex and
time consuming. 4ot only this, when compared to an array a linked list will re#uire more storage as each item has an
additional link field. Fhene!er we deal with a fixed length list its better to use an array rather than a linked list.
++++++++++++++++++
(ore on linked lists
A linked list can ha!e se!eral nodes, each with two fields. Hust what do these fields contain. Lets gi!e them a more closer
look.
As already mentioned in the pre!ious tutorial, a linked list consists of se!eral nodes where each node contains two fields,
one containing the item and the other containing the address of the next item which is in the form of a pointer. Lets take
a look at one such node'
struct node
:
int item.
struct node ,next.
?.
he first member is an integer item and the second a pointer to the next node in the list as shown below. %n this example,
we!e only considered one element item in the structure for simplicity but you could ha!e any number of elements of any
complex datatype. he pointer next is of the same structure type in which it is a member, such structures that contain a
member field that point to the same structure type are called self+referential structures.
Lets illustrate the concept of linked lists by linking two nodes. &onsider a structure
struct link
:
int num.
char nameIJ1K.
float age.
struct link ,next.
?.
struct link node0, nodeJ.
his creates two nodes of type struct link that are independent of each other. 4ow to link them, we need to make node0
point to nodeJ. his can be done if the pointer next of node0 is made to hold the address of nodeJ.
node0.next ) >nodeJ.
Assigning !alues to the other fields is done in the usual manner.
node0.num ) 0.
node0.name ) ;Dam;.
LLL..
nodeJ.num ) J.
LLL..
3o we now ha!e a list containing two nodes and any number of nodes can be created in a similar manner. For example,
nodeJ.next ) >nodeM.
would add another link pro!ided nodeM has been declared as a !ariable of type struct link.
4ow, lets say we!e created a linked list containing ten nodes, the pointer next of the last node in the list is assigned the
!alue null to indicate the end of the list.
node01.next ) 1.
++++++++++++++++++++++
&reating a linked list
%n this tutorial lets write a program to implement dynamic memory allocation and create a linear linked list interacti!ely.
o write a program to create a linear linked list interacti!ely, print the contents of the list and the total number of items in
the list.
8include
struct link
:
int num,age.
char nameIJ1K.
struct link ,next.
?.
typedef struct link node.
main*-
:
node ,ptr.
!oid create*node ,p-,print*node ,y-.
int count*node ,x-.
ptr)*node ,-malloc*si$eof*node--.
create*ptr-.
printf*;<n7rinting the elements of the list;-.
print*ptr-.
printf*;<nhe number of items in the list are ) =d;,count*ptr--.
?
!oid create*pt-
node ,pt.
:
char ans)NyN.
int i.
printf*;<n5nter the number,name > age of employee ';-.
scanf*;=d =s =d;,>pt+Onum,pt+Oname,>pt+Oage-.
printf*;<nFould you like to insert another recordP Iy6nK ';-.
scanf*;=c;,>ans-.
if*ans))NyN-
:
pt+Onext)*node ,-malloc*si$eof*node--.
create*pt+Onext-.
?
else
:
pt+Onext)1.
?
?
!oid print*node ,x-
:
node ,y.
int i.
if*x+Onext))1-
:
printf*;<n4umber ) =d<n4ame ) =s<n Age ) =d<n;,x+Onum,x+Oname,x+Oage-.
printf*;<n5nd of the list;-.
?
else
:
printf*;<n4umber ) =d<n4ame ) =s<n Age ) =d<n;,x+Onum,x+Oname,x+Oage-.
print*x+Onext-.
?
?
count*node ,m-
:
int i.
for*i)0.m+OnextQ)1.iBB-
:
m)m+Onext.
?
return*i-.
?
he program first allocates a block of memory dynamically for the first node using the malloc*- function that returns a
pointer to structure of type node that has been type defined earlier. he linked list is then created by the function create*-.
2nce the first record is entered it asks if you would like to enter another record if the answer is Eyes then the function
create*- allocates memory space for the next record and calls itself recursi!ely. %f the answer is Eno then null !alue is
assigned to the pointer !ariable next and the list ends. hese items in the list are then printed using the function print*-
which accepts a pointer to the first node as an argument. /ere again print*- is a recursi!e function that stops when it
recei!es a null pointer. 3imilarly the function count counts the number of records in the list recursi!ely and returns the
number of items to the function main*-.
+++++++++++++++++

%nserting a node
Linked lists gi!e you the flexibility of inserting new nodes anywhere in the list. All that you need to do is reset two
pointers. Find out how with this tutorial.
Rou could insert a new node in three places. at the beginning of the list, in the middle of the list between two nodes or at
the end of the list. he example gi!en here is to be integrated with the pre!ious tutorial on creating a link list. he
function insert*- re#uests for the node number where the new node has to be inserted. %f the insertion happens to be at the
beginning, then memory space is created for the new node, the !alue of the new item is assigned to it and the pointer head
is assigned to the next member. he pointer new, which indicates the beginning of the new node, is assigned to head.
/owe!er if the new item is to be inserted between two nodes then we use the find*- function recursi!ely to locate the node
and the new item is inserted after this node.
8include
main*-
:
node ,ptr.
char ans)NyN.
!oid create*node ,p-,print*node ,y-,insert*node ,#-.
int count*node ,x-.
ptr)*node ,-malloc*si$eof*node--.
create*ptr-.
printf*;<n7rinting the elements of the list;-.
print*ptr-.
printf*;<nhe number of items in the list are ) =d;,count*ptr--.
6, Additional code to be inserted with the pre!ious tutorial on creating a link list ,6
printf*;<nDo you want to insert a record Iy6nK;-.
getchar*-.
scanf*;=c;,>ans-.
if*ans))NyN-
:
insert*ptr-.
?
?
!oid insert*node ,pt-
:
node ,new,,n,,find*node ,m,int n-.
int nodenum.
char ans.
printf*;<n5nter the node number where the new record has to be inserted ';-.
scanf*;=d;,>nodenum-.
new)*node ,-malloc*si$eof*node--.
printf*;<n5nter the record number,name > age';-.
scanf*;=d =s =d;,>new+Onum,new+Oname,>new+Oage-.
if*r+Onum))nodenum-
:
new+Onext)pt.
pt)new.
print*pt-.
?
else
:
n)find*pt,nodenum-.
new+Onext)n+Onext.
n+Onext)new.
print*pt-.
?
printf*;<nFould you like to insert another record Iy6nK';-.
getchar*-.
scanf*;=c;,>ans-.
if*ans))NyN-
:
insert*pt-.
?
else
:
print*pt-.
?
?
node ,find*node ,x,int y-
:
if*x+Onum))y-
:
return*x+Onext-.
?
else if*x+Onext))1-
:
printf*;<n4ode not found;-.
return.
?
else
:
find*x+Onext,y-.
?
?
+++++++++++++++++++++++++++
Deleting a node
4ow that we know how to create a linked list and insert nodes into the list lets also find out how to delete a node from the
list with this tutorial.

As in the case of inserting a node into a linked list, we ha!e three situations while deleting a node. hese are deleting the
first node, deleting a node from the middle of the list and deleting the last node. Lets take a look at a function to delete a
specified node, this again has to be integrated into the code for creating a node. As we proceed with the code we will
mention the additional code thats to be added to the creating and inserting into a linked list.
main*-
:
node ,ptr, ,delete*node ,n-, insert*node ,#-.
char ans)NyN.
!oid create*node ,p-,print*node ,y-.
int count*node ,x-.
ptr)*node ,-malloc*si$eof*node--.
create*ptr-.
printf*;<n7rinting the elements of the list;-.
print*ptr-.
printf*;<nhe number of items in the list are ) =d;,count*ptr--.
printf*;<nDo u want to insert an item Iy6nK;-.
getchar*-.
scanf*;=c;,>ans-.
if*ans))NyN-
:
insert*ptr-.
?
6, Additional code added to main to delete a record ,6
printf*;<nDo you want to delete an item Iy6nK;-. getchar*-.
scanf*;=c;,>ans-.
if*ans))NyN-
:
delete*ptr-.
?
?
node ,delete*node ,d-
:
node ,!al, ,temp.
int nodenum.
char ans.
printf*;<n5nter the node number that has to be deleted ';-.
scanf*;=d;,>nodenum-.
if*nodenum))d+Onum-
:
!al)d+Onext.
free*d-.
d)!al.
?
else
:
!al)find*d,*nodenum+0--.
if*!al))1-
:
printf*;<n4ode not found;-.
?
else
:
temp)!al+Onext+Onext.
free*!al+Onext-.
!al+Onext)temp.
?
?
print*d-.
printf*;<nDo you want to delete another recordIy6nK ';-.
getchar*-.
scanf*;=c;,>ans-.
if*ans))NyN-
:
delete*d-.
?
else
:
return*d-.
?
?
/ere the function first checks whether the specified item is the first node. %f yes, then the pointer to the second node is
temporarily assigned to the pointer !ariable !al. hen the memory space occupied by the first node is freed and the
location of the second node is assigned to the pointer d. /ence what was pre!iously the second node now becomes the first
node.
%f the item to be deleted is not the first one then the function find*- *the code for which is gi!en in the pre!ious tutorial to
insert a node- is used to locate the position of the node to be deleted. /ere the !alue passed to the function find*- is
nodenum+0.
he nodenum !alue is reduced by one, so as to obtain the location of the node prior to the node to be deleted. his is done
to bypass the node that is to be deleted. he preceding node can then be made to point to the node following the node to be
deleted. he pointers are then interchanged with the help of the temporary pointer !ariable !al. he memory space
occupied by the node to be deleted is then freed.
+++++++++++++++++++++++
(ore on preprocessor directi!es
%n this tutorial, lets take a look at how macros can be nested and how files can be included in a program to further
simplify and make it more efficient.

4esting of macros
(acro definitions can be nested thus allowing us to use one macro in the definition of another macro. For instance
consider the following definitions'
8define ( G
8define 4 (B0
8define 3S9AD5*x- **x- , *x--
8define &9A5*x- *3S9AD5*x- , *x--
the preprocessor expands each 8define macro, until no macros appear in the text. For example, the last definition
*3S9AD5*x- , *x-- is expanded into
***x- , *x-- , *x-- which is finally e!aluated as x to the power of M.
(acros can also be used as parameters of other macros. For example, gi!en the definitions of ( and 4, we can define the
following macro to gi!e the maximum of these two'
8define (AT*(,4- ***(- O *4- P *(- ' *4-
(acro calls can be nested in much the same manner as function calls. For example
8define /ALF*x- **x-6J-
8define R /ALF*/ALF*x--
3imilarly, gi!en the definition of (AT*a,b- we can use the following nested call to gi!e the maximum of the three !alues
x,y > $
(AT*x,(AT*y,$--
9ndefining a (acro
A defined macro can be undefined using the statement
8undef identifier
9ndefining a macro can be useful when we want to restrict the definition to a particular part of the program.
File %nclusion
Any function that is used by se!eral different programs can be placed in a separate program by itself and can be included
in the other programs using the preprocessor directi!e. his makes the program more efficient and we need not rewrite
those functions time and again. his is how it can be done
8include ;filename;
8include
%n the first directi!e the filename within #uotes is the name of the file containing the re#uired definitions or functions. At
this point in the program, the preprocessor inserts the entire contents of ;filename; into the source code of the program.
4ote the difference between the two directi!es, the search for the first file placed within #uotes is made first in the current
directory and then in the standard directories. Fhile in the second instance the file is searched for only in the standard
directories.
Lets assume we!e created a file called test.c that contains some test functions, this file can be included in another
program in the following manner
8include
8include ;test.c;
8define ( 011
main*-
:
LLLL.
?
4esting of included files is allowed i.e. an included file can include other files. /owe!er, a file cannot include itself. %f an
included file is not found, an error is reported and compilation is terminated.
++++++++++++++++++++++++++++++++

Das könnte Ihnen auch gefallen