Ash
Ash

Reputation: 186

Unknown behaviour due to memset function

I'm trying to create a memory eating binary. So, I used malloc in while loop for allocating 1MB in one iteration.

I find some unkown behaviour, if I just allocate memory using malloc then the MemFree in /proc/meminfo is not decreasing as expected.

If I allocate the memory and do some memset then the MemFree in /proc/meminfo is decreasing properly.

Below is the code :

int main()
{
char *temp,*cmd="cat /proc/meminfo | grep MemFree";
    int i=0;

    while(1)
    {
    temp=malloc(1024*1024);
    //memset(temp,1,1024*1024);  //If not commented then MemFree is updated properly
    if(temp == NULL)
        printf("failed \n");
    else printf("allocated %d   %x MB\n",++i,(unsigned int)temp);
    temp=temp;
    system(cmd);
    usleep(1000*700);
    }
}

Thanks in Advance !!

Upvotes: 2

Views: 195

Answers (2)

Magisch
Magisch

Reputation: 7352

Simply allocating memory will not mean the kernel will reserve that much physical memory for your program. Because of the practice of over allocating, which many many applications are regularly guilty of, the kernel just assumes that unless you are currently writing to or reading from that memory, you don't actually need it.

To make your program actually use that memory, have it write to it with random, garbage or even just set values.

Upvotes: 2

unwind
unwind

Reputation: 399813

So, I guess your actual question is "why does it look like my program isn't using memory, unless I add code to write to it?" or something.

This is because the kernel is being lazy and hoping your application is over-allocating. Once you actually touch the memory, it has to do the work to make that memory available, and thus the measured actual memory use for that process changes then.

Upvotes: 2

Related Questions