Heap Memory 123
}31
total = sum (arr , length );32
printf (" Total is % d. n" , total );33
free ( arr );34
return EXIT _SUCCES S ;35
}36
In this example, arr is passed to function sum as an argument. The sum function itself
does not need to know whether the value in array is an address in stack memory or heap
memory. The function only needs to know that array contains a valid address somewhere
in memory. The address is copied when it is passed as the argument array in the function
called sum. The call stack and the heap memory look like the following inside the sum
function, just before the for block starts:
Frame Symbol Address Value Address Value
sum
answer 211 0 10044 11
iter 210 - 10040 10
length 209 12 10036 9
array 208 10000 10032 8
value address 207 205 10028 7
return location 206 line 33 10024 6
main
total 205 ? 10020 5
length 204 12 10016 4
iter 203 13 10012 3
arr 202 10000 10008 2
argv 201 - 10004 1
argc 200 - 10000 0
(a) Stack Memory (b) Heap Memory
Inside sum, array[0] refers to the value stored at 10000 and it is 0. Similarly, array[7]
refers to the value stored at 10028 (10000 + 7 × sizeof(int)) and it is 7.
In the following example, the function multi2 doubles the array elements:
// double . c1
#in clude < stdio .h >2
#in clude < stdlib .h >3
void multi2 ( in t * array , in t length )4
{5
int iter ;6
for ( iter = 0; iter < length ; iter ++)7
{8
array [ iter ] *= 2;9
}10
}11
int main ( i n t argc , char * argv [])12
{13
int * arr ;14
int iter ;15
int length = 12;16
arr = malloc ( length * s i z e o f ( i n t ) );17
i f ( arr == NULL )18
{19
124 Intermediate C Programming
printf (" malloc fails . n") ;20
return EXIT _FAILUR E ;21
}22
for ( iter = 0; iter < length ; iter ++)23
{24
arr [ iter ] = iter ;25
}26
27
printf (" Original array : ");28
for ( iter = 0; iter < length ; iter ++)29
{30
printf (" %2 d " , arr [ iter ]) ;31
}32
printf (" n" );33
34
multi2 ( arr , length );35
36
printf (" New array : " );37
for ( iter = 0; iter < length ; iter ++)38
{39
printf (" %2 d " , arr [ iter ]) ;40
}41
printf (" n" );42
43
free ( arr );44
return EXIT _SUCCES S ;45
}46
The output of this program is shown below:
Original array: 0 1 2 3 4 5 6 7 8 9 10 11
New array: 0 2 4 6 8 10 12 14 16 18 20 22
Remember free must be called before the program ends, otherwise, the program has
a memory leak. Also, to make the program easier to understand and easier to debug, the
program should call malloc and free in the same function. If a program calls malloc and
free in different functions, then it becomes much harder to track whether:
1. memory allocated by calling malloc is released by calling free later or,
2. memory released by calling free has been allocated by calling malloc earlier.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset