I have written a program to allocate some memory as given by cmd line argument. It creates an array to consume some amount of memory, and it goes through the array for 30 seconds.
When I run it, I cant see any change in memory usage(edit: I didnt mean gradual change of memory usage, the problem was no memory was initialized due to a missing line of code) of the program. I have tried this both in Windows using Task Manager and in Linux with free() utility.
I am a beginner in C so I am afraid that I might be missing something basic. I thank you for your time to look into this and appreciate your help.
Edit: I for some reason deleted what C was meant to be. Feeling stupid now.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(int argc, char* argv[]) //for getting cmd line arg of size in MB
{ int d=atoi(argv[1]), b=0, c=0, i=0; //store the value into an integer
b=d*1024*1024; //convert MB to B
/*initially missing line below, this fixes the original issue*/
c=b/4; //int being 4 bytes each elements will be 1/4th of total B
/*missing line ends*/
printf("value passed to array size\n- %d",b); //show total size to allocate in B
int *num = (int *)malloc(b); //allocating b bytes
time_t sec = 30; //setting timer to 30secand then looping for said time
time_t startT=time(NULL);
while (time(NULL) - startT < sec)
{
for(i=0;i<c;i ) //going through each entry in the array and assigning it its position as value
{
num[i]=i;
}
}
}
CodePudding user response:
I had missed a critical line, c=b/4. As pointed out by MikeCAT and WhozCraig. Its fine now.
CodePudding user response:
To see increased memory consumption increase you allocate some memory every iteration:
int main(int argc, char *argv[])
{
size_t size = atoi(argv[1]);
printf("value passed to array size %zu\n", size);
int *num = NULL;
time_t sec = 30;
time_t startT=time(NULL);
while (time(NULL) - startT < sec)
{
int *tmp = realloc(num, size * 1024 *1024);
if(!tmp)
{
free(num);
break;
}
num = tmp;
for(size_t i=0; i< size * 1024 *1024 / sizeof(*num);i )
{
num[i]=i;
}
size *= 2;
}
}