Sie sind auf Seite 1von 24

DynamicMemoryAllocation

Dynamicmemoryallocation
Howtoallocatememoryforvariables(esp.arrays/strings)
during run time
duringruntime
malloc(),calloc(),realloc(),andfree()

CSE251Dr.CharlesB.Owen
ProgramminginC

Whydynamicmemoryallocation?
Usually,sofar,thearraysandstringswereusinghave
fixedlength(i.e.,lengthisknownatcompiletime)
Example:
charmyStr[11];//allocatesmemoryfor10chars
h
[ ]
// ll
f
h
printf(Enterastring:);
fgets(myStr, 11, stdin);
fgets(myStr,11,stdin);

Whatiftheuserwantsto
enter a string more than 10
enterastringmorethan10
charslongorifthelengthis
knownonlyatruntime?
y
2

CSE251Dr.CharlesB.Owen
ProgramminginC

malloc()
malloc()isusedtorequestadditionalmemoryfromthe
operatingsystemduringprogramexecution
Syntax:malloc(numBytes)
Inputisthenumberofconsecutivebytestobeallocated
Returnvalueisapointer tothebeginningoftheblockof
memoryallocatedorNULLifmalloc fails
Tousemalloc(),youmust#include<stdlib.h>

CSE251Dr.CharlesB.Owen
ProgramminginC

malloc()
char*charP;/*declareapointertochar*/
h * h P
/* d l
i
h */
charP

charP =malloc(10);
charP
malloc(10);

10 bytes or chars
10bytesorchars

charP

charPcontainstheaddressofthebeginningofthatblock.

CSE251Dr.CharlesB.Owen
ProgramminginC

free()
Thefunctionfree()returnsmemorytothememory
pool.Itfreesupmemory
Syntax:free(ptr)
where
whereptr
ptr points
pointsto
tomemorypreviouslyallocatedby
memory previously allocated by
malloc()function

Tousefree(),youmust#include<stdlib.h>

CSE251Dr.CharlesB.Owen
ProgramminginC

Example

Thisprogramallowstheuserto
specify the length of a string
specifythelengthofastring,
allocatesmemoryforthestring,and
pp
g p
thenappliesstringoperations

CSE251Dr.CharlesB.Owen
ProgramminginC

#include<stdlib.h>
#include<stdio.h>
#include<string.h>

/*youneedthislibraryformalloc(),free(),exit()*/
/*youneedthislibraryforstrchr(),strlen()*/

int main()
{
char*charP,*q;
, q;
int maxlen;
printf("Entermaximumstringlength:");
scanf("%d"
scanf(
%d ,&maxlen);
&maxlen);
getchar();
/*readsthenewlinecharacter*/
printf("Enterthestring:");
p
(
g )
fgets(charP,maxlen,stdin);
if((q=strchr(charP,'\n'))!=NULL)
*q='\0';
printf("You'veenteredastring%soflength%d\n",charP,strlen(charP));
free(charP);
}
7

CSE251Dr.CharlesB.Owen
ProgramminginC

Whatitdoes:
if((q=strchr(charP,'\n'))!=NULL)
*q='\0';
Thefunctionfgets returnstheentirelineinputbytheuserincludingthe
newlineattheend(whentheuserhitreturn).Thefunctionstrchr(charP,\n)
will return a pointer to that character (newline) if it exists or NULL otherwise If
willreturnapointertothatcharacter(newline)ifitexistsorNULLotherwise.If
theresultinthevariableqisnotNULL,theifstatementexecutesthelineof
codetoreplacethenewlinewithanullterminationforthestring.

CSE251Dr.CharlesB.Owen
ProgramminginC

strchr
if((q=strchr(charP,'\n'))!=NULL)
*q='\0';

Thiscodefindsthefirstoccurance ofthe
character\nwhichisthenewlinecharacter
that fgets willobtain.Iffound(valueinqis
thatfgets
will obtain If found (value in q is
notNULL),itsetsthatcharactertothestring
nulltermination.

CSE251Dr.CharlesB.Owen
ProgramminginC

Memoryleak
Ifmalloced memoryisnotfreeed,thentheOSwill
leakmemory
Thismeansthatmemoryisallocatedtotheprogrambut
notreturnedtotheOSwhenitisfinishedusingit
Theprogramthereforegrowslargerovertime.
The program therefore grows larger over time

10

CSE251Dr.CharlesB.Owen
ProgramminginC

int main()
{Example
char*charP,r[80];
int length;

Memoryleakexample

while(1)
{
printf("Enterthemaximumstringlength:");
fgets(r,80,stdin);
sscanf(r,"%d",&length);
if((charP =malloc(length))==NULL){
printf("Outofmemory.Quitting\n");
exit(1);
( );
}
printf("Enterthestring:");
fgets(charP,length,stdin);
/*free(charP);*/
}
}

11

CSE251Dr.CharlesB.Owen
ProgramminginC

int main()
{Example
char*charP,r[80];
int length;

Memoryleakexample
Eachiterationoftheloopallocatesmemory
Each
iteration of the loop allocates memory
forastring.But,thatmemoryisneverfreed.
Hence,wehaveamemoryleak.

while(1)
{
printf("Enterthemaximumstringlength:");
fgets(r,80,stdin);
sscanf(r,"%d",&length);
if((charP =malloc(length))==NULL){
printf("Outofmemory.Quitting\n");
exit(1);
( );
}
printf("Enterthestring:");
fgets(charP,length,stdin);
/*free(charP);*/
}
}

12

CSE251Dr.CharlesB.Owen
ProgramminginC

mallocwithoutfreeing

while(1)
{
charP =malloc(length+1);
= malloc(length+1);

charP

Ifyoudontfreetheallocatedmemory,previousblockisstillours
accordingtotheOS,butwecannolongerfindit(nopointertoit).That
blockisanorphan!
Itslikeyouboughtahouse,butthenlostthe
address You still own it and pay taxes on it but
address.Youstillownitandpaytaxesonit,but
youcantuseitbecauseyoucantfindit.

13

CSE251Dr.CharlesB.Owen
ProgramminginC

Alwaysfreewhatyoumalloc
Youareresponsibleforyourmemory,youmust
allocateitandfreeit.
Unlikeotherlanguages,itisalluptoyou!
Ifyoudontfreeit,yourprogramgrowslargerand
eventuallyrunsoutofmemory!

14

CSE251Dr.CharlesB.Owen
ProgramminginC

mallocallocatesbytes
Ifyouwantacharacterarraythatstores10
characters(including\0):
char*p=malloc(10);

If
Ifyouwanttoallocatestoragefor10ints
t t ll t t
f 10 i t (ordoubles
( d bl
orfloats),youcantdothis:
int *p
p=malloc(10);
= malloc(10);

15

//*WRONG!Why?
WRONG! Why? *//

CSE251Dr.CharlesB.Owen
ProgramminginC

allocateintanddoublearray
int *intP;
double*doubleP;
//Allocatespacefor10integers
intP =malloc(10
= malloc(10 *sizeof(int));
sizeof(int));
//Allocatespacefor10doubles
doubleP =malloc(10*sizeof(double));

16

CSE251Dr.CharlesB.Owen
ProgramminginC

allocateintanddoublearray
int *intP;
double*doubleP;
//Allocatespacefor10integers
intP =malloc(10
= malloc(10 *sizeof(int));
sizeof(int));

Allocates40bytes
sizeof(int)=4

//Allocatespacefor10doubles
doubleP =malloc(10*sizeof(double));
Allocates80bytes
sizeof(double)=8

17

CSE251Dr.CharlesB.Owen
ProgramminginC

realloc
realloc takesapointertoallocatedmemoryand
reallocatesthememorytoalargersize
ifitcanmaketheoldblockbigger,great
ifnot,itwillgetanother,largerblock,copytheold
contents to the new contents free the old contents and
contentstothenewcontents,freetheoldcontentsand
returnapointertothenew
intP =malloc(sizeof(int));
= malloc(sizeof(int));
intP =realloc(intP,2*sizeof(intP));
intP maybedifferentafterarealloc!

18

CSE251Dr.CharlesB.Owen
ProgramminginC

int main()
{
double*dblPtr;
int howMany,randNum;
howMany randNum

Step1: Prompttheusertoenter
thenumberofrandomnumbersto
generate

printf("Howmanyrandomnumberstogenerate:");
howMany=ProcessInput(stdin);
dblPtr =malloc(howMany *sizeof(double));
if(dblPtr ==NULL)
{
printf("memory
printf(
memoryallocationerror,exiting\n
allocation error exiting\n");
);
exit(1);
}

Anexampleprogram
p p g

for(int i=0;i<howMany;i++)
{
randNum =random();
dblPtr[i]=(randNum%10000)/1000 0;
dblPtr[i]=(randNum%10000)/1000.0;
}
PrintArray(dblPtr,howMany);

19

CSE251Dr.CharlesB.Owen
ProgramminginC

int main()
{
double*dblPtr;
int howMany,randNum;
howMany randNum

Step2: createadynamicarrayto
storetherandomnumbers

printf("Howmanyrandomnumberstogenerate:");
howMany=ProcessInput(stdin);
dblPtr =malloc(howMany *sizeof(double));
if(dblPtr ==NULL)
{
printf("memory
printf(
memoryallocationerror,exiting\n
allocation error exiting\n");
);
exit(1);
}

Inthisexamplewehave
testedtobesuremalloc
succeeded.Ifnot,weare
outofmemory.

for(int i=0;i<howMany;i++)
{
randNum =random();
dblPtr[i]=(randNum%10000)/1000 0;
dblPtr[i]=(randNum%10000)/1000.0;
}
PrintArray(dblPtr,howMany);

20

CSE251Dr.CharlesB.Owen
ProgramminginC

int main()
{
double*dblPtr;
int howMany,randNum;
howMany randNum

Step3: generatetherandom
numbersandprintthem

printf("Howmanyrandomnumberstogenerate:");
howMany=ProcessInput(stdin);
dblPtr =malloc(howMany *sizeof(double));
if(dblPtr ==NULL)
{
printf("memory
printf(
memoryallocationerror,exiting\n
allocation error exiting\n");
);
exit(1);
}
for(int i=0;i<howMany;i++)
{
randNum =random();
dblPtr[i]=(randNum%10000)/1000 0;
dblPtr[i]=(randNum%10000)/1000.0;
}
PrintArray(dblPtr,howMany);

21

CSE251Dr.CharlesB.Owen
ProgramminginC

dblPtr =realloc(dblPtr,2*howMany);

for(int i=howMany;i<howMany*2;i++)
{
randNum =random();
dblPtr[i]=(randNum%10000)/1000.0;
}

Step4: doublethesizeofthearrayusing
realloc

Step5: generatemorerandom
numbersandprintthem

howMany *=2;
PrintArray(dblPtr,howMany);
PrintArray(dblPtr
howMany);
free(dblPtr);
}

22

CSE251Dr.CharlesB.Owen
ProgramminginC

int ProcessInput(FILE*f)
p (
)
{
int val;
Safedataentry,justlikelast
y, j
week
charin[100];
fgets(in,100,f);
sscan(in,%d,&val);
returnval;
}

23

CSE251Dr.CharlesB.Owen
ProgramminginC

PrintArray
voidPrintArray(double*ptr,int cnt)
{
printf("PrintingArrayValues\n");
(
p p ; p p
; p )
for(double*p=ptr;p<ptr+cnt;p++)
printf("Valis:%lf\n",*p);
}

24

CSE251Dr.CharlesB.Owen
ProgramminginC

Das könnte Ihnen auch gefallen