Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Due to these lines</p> <pre><code>char* buffer = (char*) malloc(16 * sizeof(char)); size_t allocated = 1; </code></pre> <p>the program shrinks <code>buffer</code> for the first 4 re-allocations. So the program writes to un-allocated memory from <code>i=16</code> on, which is undefined behaviour, so anything could happend. Also this most likely smashes the memory management which in turn makes <code>realloc()</code> fail.</p> <p>You might like to change those two lines to be:</p> <pre><code>size_t allocated = 16; /* or = 1 if the 16 was a typo. */ char * buffer = malloc(allocated); </code></pre> <p>Other notes: </p> <ul> <li><code>sizeof(char)</code> is always <code>1</code>.</li> <li>Do not cast the result of <code>malloc/calloc/realloc</code> as it is not necessary nor recommended: <a href="https://stackoverflow.com/a/605858/694576">https://stackoverflow.com/a/605858/694576</a>.</li> <li>Do check the result of system calls.</li> </ul> <p>Refering the last note, the following modifications should be applied</p> <pre><code>char * buffer = malloc(allocated); </code></pre> <p>might become:</p> <pre><code>char * buffer = malloc(allocated); if (NULL == buffer) { /* Error handling goes here. */ } </code></pre> <p>and</p> <pre><code>buffer = (char*) realloc(buffer, allocated * sizeof(char)); </code></pre> <p>might become:</p> <pre><code>{ char * pctmp = realloc(buffer, allocated); if (NULL == pctmp) { /* Error handling goes here. */ } else { buffer = pctmp; } } </code></pre>
 

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