Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you are just looking for a unified way (without code duplication) to check if allocation was successful or not, please see the last segment of this post.</p> <hr> <p>First of all <code>boost</code> is mainly a library for <code>C++</code>, therefor all of <code>boost</code> can't be used in C.</p> <p>Writing your own Garbage Collector is not easy, especially in a language without true OOP (such as <code>C</code>). There are many implementations of garbage collectors available online, so instead of reinventing the wheel you could check out some of them.</p> <p>If you are not going to use any of them, well.. at least they will provide you with some information regarding how the problem can be solved.</p> <ul> <li><a href="http://www.hpl.hp.com/personal/Hans_Boehm/gc/" rel="nofollow">A garbage collector for C and C++ (Boehm-Demers-Weiser) <strong>[recommended]</strong></a></li> <li><a href="http://developers.sun.com/solaris/articles/libgc.html" rel="nofollow">Using the C/C++ Garbage Collection Library, libgc</a></li> </ul> <hr> <p>Depending on the project size you might be better of using <a href="http://valgrind.org/" rel="nofollow"><code>valgrind</code></a> looking for leaking data and then manage the memory allocation/release by yourself.</p> <p>C has been around for many years, and a lot of developers have managed without a automatic garbage collector. Why shouldn't you be able to do the same?</p> <hr> <h2>Simple error checking on allocation (and abort on error)</h2> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; void* safe_alloc_check (void *p, size_t size) { if (p == NULL) { printf ("ERROR: Unable to allocate memory for %lu bytes!", size); exit (-1); } return p; } #define s_malloc(N) safe_alloc_check(malloc(N),N) #define s_calloc(C,N) safe_alloc_check(calloc(C,N),N) #define s_realloc(P,N) safe_alloc_check(realloc(P,N),N) ... int *p = s_malloc (sizeof (int)); </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.
 

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