0

I have allocated 1GB of memory dynamically using malloc using following program.

#include <malloc.h>
#include <stdio.h>

int main()
{
        int i;
        char **ptr = malloc(10000 * sizeof(char*));

        // Dynamically allocate 1GB of space
        for (i=0; i<10000; i++) {
                ptr[i] = malloc(1024 * 100 * sizeof(char));
                ptr[i] = "How do you do?";
                ptr[6888] = "How are you?";
        }

        // Print string at some random locations
        printf("%s\n", ptr[3688]);
        printf("%s\n", ptr[6888]);
        printf("%s\n", ptr[6889]);
        getchar();
        return 0;
}

Output:

jobin@gnome:~$ ./a.out 
How do you do?
How are you?
How do you do?

RAM usage before execution of program:

jobin@gnome:~$ free -h
             total       used       free     shared    buffers     cached
Mem:          2.9G       2.0G       981M        16M        28M       569M
-/+ buffers/cache:       1.4G       1.5G
Swap:           0B         0B         0B

RAM usage during execution of program:

jobin@gnome:~$ free -h
             total       used       free     shared    buffers     cached
Mem:          2.9G       2.0G       945M        16M        28M       569M
-/+ buffers/cache:       1.4G       1.5G
Swap:    

   0B         0B         0B

The output seems to be fine. But I expect RAM usage should be 1GB higher during execution of the program. But it seems quite normal. I don't think OS did garbage collection on the memory. If OS free up the memory which I have allocated, I won't get the output and possibly a segmentation fault on execution.

Note: I am using ubuntu.

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Jobin
  • 6,506
  • 5
  • 24
  • 26
  • 1
    a) C++ or C? b) Learn what strcpy is. c) Learn what free is. d) You're not writing to most of the memory, eg. "How do you do" is never written anywhere. – deviantfan Jul 02 '16 at 10:21
  • @ deviantfan, You are right, I should use strcpy. – Jobin Jul 02 '16 at 10:38

1 Answers1

3

Normally the OS will only actually allocate the memory once you write to it. Up until that point it doesn't need to and can save a lot if you never write to it or only write to part of it.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70