Are you running this code with root
privilege? Once I also tried memory allocation code with user
privilege and I got error.
This is not your answer, But I want to share my sample code here, May be we can learn something from this. With this approach we can allocate required amount of memory until memory running out.Well this is working code (If you tried for more memory, then it will give error).
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#define A_MEGABYTE (1024 * 1024)
#define PHY_MEM_MEGS 1024 /* Adjust this number as required */
int main()
{
char *some_memory;
size_t size_to_allocate = A_MEGABYTE;
int megs_obtained = 0;
while (megs_obtained < (PHY_MEM_MEGS * 2))
{
some_memory = (char *)malloc(size_to_allocate);
if (some_memory != NULL)
{
megs_obtained++;
sprintf(some_memory, “Hello World”); //Message to check
printf(“%s - now allocated %d Megabytes\n”, some_memory, megs_obtained);
}
else
{
exit(EXIT_FAILURE);
}
}
exit(EXIT_SUCCESS);
}
May be this can help.
EDIT
This is upto my understanding, Please let me know if I am wrong.
As you said you are getting 2.5 GB
of memory, this is because heap can allocate 2/3 times
of its memory. So you will get Max 3 GB
from 4 GB
of memory. Rest memory occupied by some processes and definitely process scheduler
. No intelligent OS allow itself for suicide.
Here I read Operating System
book of Galvin
. According to the book in your case if you want to allocate more memory just call malloc
1000 times (single line for each malloc call), or upto the Page Size
of OS. Until you swap pages in memory you will not get Kernel Message
(Theoretically). Your page is not swaped out from memory, this is the only problem.
Between if you want to check all your Swap area
write this code with Thread
with sleep
so you can check what all processes are in swap memory.
I did not write any code for that so please update us if you write some code.