title: Linux- Out of Memory
body: <p>I was trying to see the working of oom_kill by invoking manually.</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>Sample codes of both:</p>
  
  <p>First case: while:</p>
  
  <pre><code>int main (void) {
  char* p;
          while (1) {
                  p=malloc(1&lt;&lt;20);
                  memset (p, 0, (1&lt;&lt;20));       
                  }
                 }
  </code></pre>
  
  <p>Second case : for : </p>
  
  <pre><code>int main (void) {
          int i, n = 0;
          char *pp[N];
  
          for (n = 0; n &lt; N; n++) {
                  pp[n] = malloc(1&lt;&lt;20);
                  if (pp[n] == NULL)
                          break;
          }
          printf("malloc failure after %d MiB\n", n);
  
          for (i = 0; i &lt; n; i++) {
                  memset (pp[i], 0, (1&lt;&lt;20));
                  printf("%d\n", i+1);
          }
  </code></pre>
  
  <p>where N is some very large number to invoke oom. Referred this <a href="https://www.win.tue.nl/~aeb/linux/lk/lk-9.html" rel="nofollow noreferrer">https://www.win.tue.nl/~aeb/linux/lk/lk-9.html</a> for 2nd case.</p>
  
  <p>Why does it happen so? What is the mistake I'm making with the while loop?</p>
  
  <p>Kernel version : 4.15 </p>