Linux- Out of Memory

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Linux- Out of Memory



I was trying to see the working of oom_kill by invoking manually.



I allocated memory dynamically and tried to use them infinitely with while loop at first and then with the for loop to test out of memory.



But in the first case where I used the while loop it threw segmentation fault without swap and became unresponsive with swap whereas with the for loop out of memory (oom_kill) was invoked.



Sample codes of both:



First case: while:


int main (void) {
char* p;
while (1) {
p=malloc(1<<20);
memset (p, 0, (1<<20));
}
}



Second case : for :


int main (void) {
int i, n = 0;
char *pp[N];

for (n = 0; n < N; n++) {
pp[n] = malloc(1<<20);
if (pp[n] == NULL)
break;
}
printf("malloc failure after %d MiBn", n);

for (i = 0; i < n; i++) {
memset (pp[i], 0, (1<<20));
printf("%dn", i+1);
}



where N is some very large number to invoke oom. Referred this https://www.win.tue.nl/~aeb/linux/lk/lk-9.html for 2nd case.



Why does it happen so? What is the mistake I'm making with the while loop?



Kernel version : 4.15




2 Answers
2



The document you're reading is from 2003. The impossibly large number it chose to allocate was 10,000 MiB.



Today, in 2018, when new computers are likely to come with 16GiB of RAM, this kind of allocation could definitely succeed without issues.



What is the mistake I'm making with the while loop?



The segmentation fault is likely the result of passing a null pointer to memset(), since malloc() will return NULL on error.



Your second example avoids this error by always checking the return value from malloc().



I used the while loop it ... became unresponsive with swap ...



From the very document that you mentioned that you are reading:



Sometimes processes get a segfault when accessing memory that the kernel is unable to provide, sometimes they are killed, sometimes other processes are killed, sometimes the kernel hangs.



Other than mentioning the kernel version, you are very vague with the OS and system description. Presumably this is a 32-bit version?



There are actually two ways of running out of memory. Your program could exceed the amount of (virtual) memory that is allocated, or the system could actually run out of memory pages.
Note that availability of memory (pages) is a complex combination of physical memory size, swap space size, memory usage and process load.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

C# - How to create a semi transparent or blurred backcolor on windows form

Will Oldham

Makefile test if variable is not empty