Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Memory fragmentation in C: Design, implement, and execute a C-program that does

ID: 669356 • Letter: M

Question

Memory fragmentation in C: Design, implement, and execute a C-program that does the following: It allocates memory for a sequence of 3m arrays of size 400,000 elements each; then it explicitly deallocates all even-numbered arrays and allocates a sequence of m arrays of size 600,000 elements each. Measure the amounts of time your program requires for the allocation of the first sequence and for the second sequence. Choose m so that you exhaust almost all of the main memory available to your program. Explain your timings!!

Explanation / Answer

#include <iostream>
#include <time.h>
#include <algorithm>

void main(){
clock_t begin1, stop1, begin2, stop2;
double tdif = 0, tdif2 = 0;
for(int k=0;k<1000;k++){
double dif, dif2;
const int m = 50000;
begin1 = clock();
printf("Step One ");
int *container[3*m];
for(int i=0;i<(3*m);i++)
{
int *tmpAry = (int *)malloc(500000*sizeof(int));
container[i] = tmpAry;
}
stop1 = clock();
printf("Step Two ");
for(int i=0;i<(3*m);i+=2)
{
free(container[i]);
}
begin2 = clock();
printf("Step Three ");
int *container2[m];
for(int i=0;i<m;i++)
{
int *tmpAry = (int *)malloc(700000*sizeof(int));
container2[i] = tmpAry;
}
stop2 = clock();
dif = (stop1 - begin1)/1000.00;
dif2 = (stop2 - begin2)/1000.00;
tdif+=dif;
tdif/=2;
tdif2+=dif2;
tdif2/=2;
}
printf("To Allocate the first array it took: %.5f ",tdif);
printf("To Allocate the second array it took: %.5f ",tdif2);
system("pause");
};