tags:

views:

104

answers:

3

gah..!! Forgot basics...some how this free is not working, i ran program on windows and followed memory usage using task manager, which didn't show any reduction in memory usage after free statement.

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    int i=0,j,k;
    char **ptr;

    ptr = (char **)malloc(sizeof(char *)*10);
    for (i=0;i<10;i++)
    ptr[i] = (char *)malloc(sizeof(char)*5);

    for (i=0;i<10;i++) //this loop has no significance
        for (j=0;j<5;j++)
           ptr[i][j] = 'r';

    for (i=0;i<10;i++)  //this loop has no significance
    {
        for (j=0;j<5;j++)
           printf("%c ",ptr[i][j]);
     printf("\n");
    }

    for (i=0;i<10;i++)
    free(ptr[i]);

    //at this point also program takes memory same as before

    free(ptr);
    //at this point also program takes memory same as before

    system("PAUSE");
    return EXIT_SUCCESS;
}
+10  A: 

Typical C implementations do not return free:d memory to the operating system. It is available for use by the same program, but not to others.

Thomas Padron-McCarthy
so, my syntax is absolutely correct?
calvin
calvin: Yes, there is nothing wrong with your program. It's just that the C run-time keeps the memory in the process.
Thomas Padron-McCarthy
(Well, there is one thing: You include iostream, but then use stdio. But that doesn't matter for the memory usage.)
Thomas Padron-McCarthy
+1  A: 

Note that the Task manager will show the memory "borrowed" by libc from the system. But not all mallocs will go through libc to the operating system and similarly not all free will free the system memory.

Usually, libc will allocate memory in larger chunks to supply for several malloc calls.

Viliam
+2  A: 

You can not assume that just after doing the free the memory will be returned back to OS. Generally the CRT implementation have some optimization because of which they may not return this memory immediately. This allows the CRT to allocate the subsequent memory allocation requests in a faster way.

Ponting