Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>allocp</code> should always point to the last free memory position but when there is no memory positions free it will be one beyond the end of <code>allocbuf</code>.</p> <p>Consider the situation when there is only one single memory cell left in the buffer: <code>allocp</code> will point to <code>allocbuffer[9999]</code> since that is the last free memory cell. Now when you make the function call <code>alloc(1)</code> the test</p> <pre><code>allocbuf + ALLOCSIZE - allocp &gt;= n </code></pre> <p>will return true as it should since you are trying to allocate one <code>char</code> and there is exactly one <code>char</code> left. Then the very last memory position will be allocated. Now <code>allocbuf - allocp == ALLOCSIZE</code> and is one beyond the end of <code>allocbuf</code>. But in that case the above mentioned test will always return false and thus no memory will ever be accessed beyond the scope of <code>allocbuf</code>. </p> <hr> <p>About your question regarding <code>afree</code>: The initial value of the memory returned by <code>malloc</code> is undefined. This means that you can never make any assumptions about it and must overwrite it before use. Therefore <code>afree</code> does not have to delete any data contrary to what you're assuming. It is perfectly fine for it to simply mark it as no longer in use and available for future allocation.</p> <p>On a side note there is a function very similar to <code>malloc</code> named <code>calloc</code> which after allocating the requested memory block initializes it all to zero.</p>
 

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