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.