Vous êtes sur la page 1sur 3

(http://www.studytonight.

com/)

CLANGUAGE
"Cismostwidelyusedgeneralpurposelanguagetodayinoperatingsystems,andembedded
systemdevelopment."

SEETHEINDEX

Dynamic Memory Allocation


Theprocessofallocatingmemoryatruntimeisknownasdynamicmemoryallocation.Libraryroutines
knownas"memorymanagementfunctions"areusedforallocatingandfreeingmemoryduringexecutionofa
program.Thesefunctionsaredefinedinstdlib.h.
Function

Description

malloc()

allocatesrequestedsizeofbytesandreturnsavoidpointerpointingtothefirstbyteofthe
allocatedspace

calloc()

allocatesspaceforanarrayofelements,initializethemtozeroandthenreturnavoidpointerto
thememory

free

releasespreviouslyallocatedmemory

realloc

modifythesizeofpreviouslyallocatedspace

Memory Allocation Process


Globalvariables,staticvariablesandprograminstructionsgettheirmemoryinpermanentstoragearea
whereaslocalvariablesarestoredinareacalledStack.Thememoryspacebetweenthesetworegionis
knownasHeaparea.Thisregionisusedfordynamicmemoryallocationduringexecutionoftheprogram.The
sizeofheapkeepchanging.

Allocating block of Memory


malloc()functionisusedforallocatingblockofmemoryatruntime.Thisfunctionreservesablockofmemory
ofgivensizeandreturnsapointeroftypevoid.Thismeansthatwecanassignittoanytypeofpointerusing
typecasting.IfitfailstolocateenoughspaceitreturnsaNULLpointer.
Exampleusingmalloc():
int*x;
x=(int*)malloc(50*sizeof(int));//memoryspaceallocatedtovariablex
free(x);//releasesthememoryallocatedtovariablex
calloc()isanothermemoryallocationfunctionthatisusedforallocatingmemoryatruntime.callocfunctionis
normallyusedforallocatingmemorytoderiveddatatypessuchasarraysandstructures.Ifitfailstolocate
enoughspaceitreturnsaNULLpointer.
Exampleusingcalloc():
structemployee
{
char*name;
intsalary;
};
typedefstructemployeeemp;
emp*e1;
e1=(emp*)calloc(30,sizeof(emp));
realloc()changesmemorysizethatisalreadyallocatedtoavariable.
Exampleusingrealloc():

int*x;
x=(int*)malloc(50*sizeof(int));
x=(int*)realloc(x,100);//allocatedanewmemorytovariablex

Diffrence between malloc() and calloc()


calloc()

malloc()

calloc()initializestheallocatedmemorywith0
value.

malloc()initializestheallocatedmemorywithgarbage
values.

Numberofargumentsis2

Numberofargumentis1

Syntax:

Syntax:

(cast_type*)calloc(blocks,size_of_block)

(cast_type*)malloc(Size_in_bytes)

Prev(errorhandlinginc.php)

Next(commandlineargument.php)

CheckOut: Library (http://www.studytonight.com/library) VideoCourses (http://www.studytonight.com/online


courses) Studyroom (http://www.studytonight.com/studyroom) Flashcards
(http://www.studytonight.com/flashcards)
Studytonight2014

HandcraftedwithLove

AboutUs(http://www.studytonight.com/about)Suggest(http://www.studytonight.com/suggest)Terms
(http://www.studytonight.com/terms)ContactUs(http://www.studytonight.com/contact)Collaborate
(http://www.studytonight.com/collaborate/)Authors(http://www.studytonight.com/authors/)Blog
(http://studytonight.tumblr.com/)

Vous aimerez peut-être aussi