Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>calloc is likely just implemented as something similar to:</p> <pre><code>void * calloc(size_t nmemb, size_t size) { size_t len = nmemb * size); void * ptr = malloc(len); if (ptr) { return memset(ptr, 0, len); } return ptr; } </code></pre> <p>So it just adds a multiply before and a clear after the malloc.</p> <p>malloc could be (but probably isn't ever) implemented as:</p> <pre><code>void * malloc(size_t size) { return realloc(NULL, size); } </code></pre> <p>since you can pass realloc a NULL pointer as the previous pointer, but malloc is most likely not implemented like that because it would slow down all mallocs and because realloc probably uses malloc.</p> <p>The main thing to know about realloc is that it is often capable of determining the actual size of the block of memory that any of the heap allocation routines returned and see if the block is big enough already or in some cases if it would be best try to shrink the block or move it.</p> <pre><code>void realloc(void * ptr, size_t size) { size_t alen = MALLOC_LENGTH_OF(ptr); // this just stands for some method of determining // the size of the block that was allocated, and could // be looking it up in a table or looking at a place // several bytes before the pointer, or some other // implementation specific thing if (0 == size) { free(ptr); return NULL; } if (alen &gt;= size) { return ptr; // big enough, and not worrying about it being too big } void new_ptr = malloc(size); // since I said that malloc most likely isn't // implemented using realloc using malloc here is ok if (new_ptr &amp;&amp; ptr) { memcpy(new_ptr, ptr, alen); } free(ptr); return new_ptr; } </code></pre> <p>Malloc is used more because it is simplest. Programmers can often make their allocations big enough to begin with that they don't have to worry about resizing them with realloc, and very often clearing the memory is not needed.</p> <p>There are different behaviors among different libraries, and you can even link programs with other versions just to get this different behavior without (usually without changing the compiler).</p> <p>Some malloc libraries are for debugging and error detection. Others may offer better performance. Some are optimized for allocating memory for several different threads at the same time, and avoid the different threads needing to lock down the entire heap to perform an allocation or free.</p> <p>All of them should provide the same semantics from the applications perspective, though. </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