2

I have allocated 1GB of memory using malloc.

#include <stdio.h>

    int main()
    {
        int *ptr = malloc(1024*1024*1024UL);
        if (ptr)
            printf("Memory Allocated\n");
        else
            printf("Allocation Failed\n");
        memset(ptr, 'a', (1024*1024*1024UL));
        getchar();
        free(ptr);
        return 0;
    }

Allocation is successful, but i don't see any difference in between the free memory.

Before running the application, my free memory:

$ free -m
              total        used        free      shared  buff/cache   available
Mem:           6906        1398        3457           7        2050        5206
Swap:          2047           0        2047

After running the command, but before pressing enter on the keyboard at the getchar() stage.

$ free -m
              total        used        free      shared  buff/cache   available
Mem:           6906        1398        3457           7        2050        5206
Swap:          2047           0        2047

There is no change at all. So, from where is the memory allocated. It is virtual memory, but it should have a mapping into physical memory which is RAM. Can anyone explain this

md.jamal
  • 4,067
  • 8
  • 45
  • 108
  • 3
    perhaps it was optimized out, try checking the assembly generated – M.M Sep 10 '19 at 03:35
  • 3
    I think compiler has optimized your code avoiding the memory allocation. You can try compiling with `-O0` option and check. – MayurK Sep 10 '19 at 03:37
  • 1
    Yes, after I compiled with -O0, i am getting the expected behavior. Thanks. – md.jamal Sep 10 '19 at 03:41
  • 2
    Possible duplicate of [Will malloc implementations return free-ed memory back to the system?](https://stackoverflow.com/q/2215259/608639), [Memory not freed after calling free()](https://stackoverflow.com/q/5365996/608639), [Force free() to return malloc memory back to OS](https://stackoverflow.com/q/27945855/608639), etc. – jww Sep 10 '19 at 05:02

0 Answers0