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.