7/24/2019 malloc detail
1/24
DynamicMemoryAllocation
Dynamicmemoryallocation
Howtoallocatememoryforvariables(esp.arrays/strings)
malloc(),
calloc(),
realloc(),
and
free()
CSE
251
Dr.
Charles
B.
Owen
ProgramminginC1
7/24/2019 malloc detail
2/24
Why
dynamic
memory
allocation?
Usually,sofar,thearraysandstringswereusinghavefixedlength(i.e.,lengthisknownatcompiletime)
Example:
char
myStr[11];
allocates
memory
for
10
chars
printf(Enterastring:);
Whatiftheuserwantsto
gcharslongorifthelengthis
knownonl atruntime?
CSE
251
Dr.
Charles
B.
Owen
ProgramminginC2
7/24/2019 malloc detail
3/24
malloc()
malloc()isusedtorequestadditionalmemoryfromtheoperatingsystemduringprogramexecution
Syntax: malloc(numBytes)
Inputisthenumberofconsecutivebytestobeallocated
ReturnvalueisapointertothebeginningoftheblockofmemoryallocatedorNULLifmalloc fails
Tousemalloc(),youmust#include
CSE
251
Dr.
Charles
B.
Owen
ProgramminginC3
7/24/2019 malloc detail
4/24
malloc()
c ar
c arP;
ec are
a
po nter
to
c ar
charP
=
charP
charP
contains
the
address
of
the
beginning
of
that
block.
CSE
251
Dr.
Charles
B.
Owen
ProgramminginC4
7/24/2019 malloc detail
5/24
free()
Thefunctionfree()returnsmemorytothememory
pool. Itfreesupmemory
Syntax:
free(ptr)
malloc()function
Tousefree(),youmust#include
CSE
251
Dr.
Charles
B.
Owen
ProgramminginC5
7/24/2019 malloc detail
6/24
Example
Thisprogramallowstheuserto,
allocates
memory
for
the
string,
and
then
a lies
strin
o erations
CSE
251
Dr.
Charles
B.
Owen
ProgramminginC6
7/24/2019 malloc detail
7/24
#include /*youneedthislibraryformalloc(),free(),exit()*/
#include
#include
/*
you
need
this
library
for
strchr(),
strlen()
*/int main()
{
char*charP,*q;
int maxlen;
printf("Enter
maximum
string
length:
");
" ",
getchar(); /*readsthenewlinecharacter*/
printf("Enter
the
string:
");
fgets(charP,
maxlen,
stdin);
if
((q
=
strchr(charP,
'\n'))
!=
NULL)
*q
=
'\0';printf("You'veenteredastring%soflength%d\n",charP,strlen(charP));
free(charP);
CSE
251
Dr.
Charles
B.
Owen
ProgramminginC7 A
7/24/2019 malloc detail
8/24
Whatitdoes:
if((q=strchr(charP,'\n'))!=NULL)
*q
=
'\0';
The
function
fgets returns
the
entire
line
input
by
the
user
including
the
newlineattheend(whentheuserhitreturn).Thefunctionstrchr(charP,\n)
.
the
result
in
the
variable
q
is
not
NULL,
the
if
statement
executes
the
line
of
code
to
replace
the
newline
with
a
null
termination
for
the
string.
CSE
251
Dr.
Charles
B.
Owen
ProgramminginC8
7/24/2019 malloc detail
9/24
strchr
if
((q
=
strchr(charP,
'\n'))
!=
NULL)
*q='\0';
This
code
finds
the
first
occurance of
thecharacter\nwhichisthenewlinecharacter
.
notNULL),itsetsthatcharactertothestring
null
termination.
CSE
251
Dr.
Charles
B.
Owen
ProgramminginC9
7/24/2019 malloc detail
10/24
Memoryleak
Ifmalloced memoryisnotfreeed,thentheOSwill
leakmemory
This
means
that
memory
is
allocated
to
the
program
but
not
returned
to
the
OS
when
it
is
finished
using
it
.
CSE
251
Dr.
Charles
B.
Owen
ProgramminginC10
7/24/2019 malloc detail
11/24
Exampleint main()
{
char
*charP,
r[80]; Memoryleakexampleint length;
while(1)
printf("Enter
the
maximum
string
length:
");
fgets(r,
80,
stdin);
sscanf(r,
"%d",
&length);
if((charP =malloc(length))==NULL){
printf("Out
of
memory.
Quitting\n");
exit 1
}
printf("Enterthestring:");
fgets(charP,length,stdin);
/*
free(charP);
*/}
}
CSE
251
Dr.
Charles
B.
Owen
ProgramminginC11 B
7/24/2019 malloc detail
12/24
Exampleint main()
{
char
*charP,
r[80];
Memoryleakexample
int length;
while(1)forastring.But,thatmemoryisneverfreed.
Hence,wehaveamemoryleak.
printf("Enter
the
maximum
string
length:
");
fgets(r,
80,
stdin);
sscanf(r,
"%d",
&length);
if((charP =malloc(length))==NULL){
printf("Out
of
memory.
Quitting\n");
exit 1
}
printf("Enterthestring:");
fgets(charP,length,stdin);
/*
free(charP);
*/}
}
CSE
251
Dr.
Charles
B.
Owen
ProgramminginC12
7/24/2019 malloc detail
13/24
mallocwithoutfreeing while(1)
{
}
charP
If
you
dont
free
the
allocated
memory,
previous
block
is
still
ours
according
to
the
OS,
but
we
can
no
longer
find
it
(no
pointer
to
it).
That
block
is
an
orphan!Itslikeyouboughtahouse,butthenlostthe
. ,
you
cant
use
it
because
you
cant
find
it.
CSE
251
Dr.
Charles
B.
Owen
ProgramminginC13
7/24/2019 malloc detail
14/24
Alwaysfreewhatyoumalloc
Youareresponsibleforyourmemory,youmust
allocateitandfreeit.
Unlikeotherlanguages,itisalluptoyou!
If
you
dont
free
it,
your
program
grows
larger
and
eventuallyrunsoutofmemory!
CSE
251
Dr.
Charles
B.
Owen
ProgramminginC14
7/24/2019 malloc detail
15/24
mallocallocatesbytes
Ifyouwantacharacterarraythatstores10
characters(including\0):
char*p=malloc(10);
youwan oa oca es orage or n s or ou es
orfloats),youcantdothis:
* * *
CSE
251
Dr.
Charles
B.
Owen
ProgramminginC15
7/24/2019 malloc detail
16/24
allocateint anddoublearray
int *intP;
double*doubleP;
//
Allocate
space
for
10
integers
*
//
Allocate
space
for
10
doublesdoubleP =malloc(10*sizeof(double));
CSE
251
Dr.
Charles
B.
OwenProgramminginC16 C
7/24/2019 malloc detail
17/24
allocateint anddoublearray
int *intP;
double*doubleP;
//
Allocate
space
for
10
integers
*
Allocates
40
bytessizeof(int)=4
//
Allocate
space
for
10
doublesdoubleP =malloc(10*sizeof(double));
Allocates80bytes
sizeof(double)
=
8
CSE
251
Dr.
Charles
B.
OwenProgramminginC17
7/24/2019 malloc detail
18/24
realloc
realloctakesapointertoallocatedmemoryand
reallocatesthememorytoalargersize
ifitcanmaketheoldblockbigger,great
ifnot,itwillgetanother,largerblock,copytheold
,
returnapointertothenew
intP =realloc(intP,2*sizeof(intP));
intP may
be
different
after
a
realloc!
CSE
251
Dr.
Charles
B.
OwenProgramminginC18
7/24/2019 malloc detail
19/24
int main
()
{
double*dblPtr;
Step1:Prompttheusertoenter
the
number
of
random
numbers
to
generate
ow y,
u ;
printf("How
many
random
numbers
to
generate:");
howMany=ProcessInput(stdin);
dblPtr =
malloc(howMany *
sizeof(double));
if
(dblPtr ==
NULL)
{
" " Anexam le ro ram
o y o o o , x ;
exit(1);
}
for(int i=0;i
7/24/2019 malloc detail
20/24
Step2:createadynamicarrayto
store
the
random
numbers
int main
()
{
double*dblPtr;
ow y,
u ;
printf("Howmanyrandomnumberstogenerate:");
howMany=ProcessInput(stdin);
dblPtr =
malloc(howMany *
sizeof(double));
if
(dblPtr ==
NULL)
{
" "
In
this
example
we
have
testedtobesuremalloc , ;
exit(1);
}
succeeded.Ifnot,weare
out
of
memory.
for(int i=0;i
7/24/2019 malloc detail
21/24
Step3:generatetherandom
numbersandprintthem
int main
()
{
double*dblPtr;
ow y,
u ;
printf("Howmanyrandomnumberstogenerate:");
howMany=ProcessInput(stdin);
dblPtr =
malloc(howMany *
sizeof(double));
if
(dblPtr ==
NULL){
" " , ;
exit(1);
}
for
(int i=0;i
7/24/2019 malloc detail
22/24
dblPtr =realloc(dblPtr,2*howMany); Step4:doublethesizeofthearrayusing
realloc
for(int i=howMany;i
7/24/2019 malloc detail
23/24
int ProcessIn ut FILE
*f{
int val; Safedataentr ustlikelast
char
in[100];fgets(in,100,f);
week
sscan(in,%d,&val);
return
val;}
CSE
251
Dr.
Charles
B.
OwenProgramminginC23
7/24/2019 malloc detail
24/24
PrintArray
voidPrintArray(double*ptr,int cnt)
{
printf("Printing
Array
Values\n");for double* = t r < tr+cnt ++
printf("Valis:%lf\n",*p);
CSE
251
Dr.
Charles
B.
OwenProgramminginC24 1
Top Related