Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A memory leak occurs when you request memory with <code>malloc()</code> and don't <code>free()</code> the memory. </p> <h1>Bad example</h1> <pre><code>#include &lt;stdlib.h&gt; int main(int argc, char *argv[]) { int *nums = malloc(10 * sizeof(int)); // create array with memory for 10 nums nums[0] = 2; nums[4] = 8; return 0; // main() ended but nums wasn't free'd. Memory leak/ } </code></pre> <h1>Good example</h1> <pre><code>#include &lt;stdlib.h&gt; int main(int argc, char *argv[]) { int *nums = malloc(10 * sizeof(int)); // create array with memory for 10 nums nums[0] = 2; nums[4] = 8; free(nums); // free memory allocated for nums return 0; } </code></pre> <p>Now about your programs.</p> <h1>1 - reformatted</h1> <p>This program will never end and forever call x (and thus print Hello World! till the end of times)</p> <pre><code>#include &lt;stdio.h&gt; void x(void) { printf("Hello World!\n"); } int main(int argc, char *argv[]) { while (1) x(); return 0; } </code></pre> <h1>2 - reformatted</h1> <p>This program allocates memory for 100 integers every loop but never free's this memory. Huge memory leak that keeps going until the OS is out of memory.</p> <pre><code>#include &lt;stdlib.h&gt; int main(int argc, char *argv[]) { int *x; while (1) { x = malloc(100 * size(int)); // allocate memory for an array of 100 integers } return 0; } </code></pre> <h1>3 - reformatted</h1> <p>This program keeps recursing until the stack is exhausted (stack trace) and the program will crash (stack overflow).</p> <pre><code>void x(void) { x(); } int main(int argc, char *argv[]) { x(); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload