Fix write length so it includes the updated header (tag) CRC32
[firmware_header_edit.git] / heap_reap.c
index db73423..cbf2494 100644 (file)
@@ -1,11 +1,9 @@
-/* experimental tracking of heap allocations for easy reaping no matter what the code path is
+/* Experimental tracking of heap allocations for easy reaping no matter what the code path is
+ * Copyright 2016 TJ <hacker@iam.tj>
+ * Licensed on the terms of the GNU General Public License version 3.
  *
- * both tasks are in the same function to take advantage of local static variables that are
+ * Both tasks are in the same function to take advantage of local static variables that are
  * persistent across calls but invisible to code outside the function.
- *
- * @param ptr   NULL: calloc(nmemb, size), NULL-1: reap all, otherwise free(ptr)
- * @param nmemb number of elements of size to allocate
- * @param size  size if each element
  */
 
 #include "heap_reap.h"
@@ -21,6 +19,11 @@ struct mem_track {
   size_t allocated;
 };
 
+/* 
+ * @param ptr   NULL: calloc(nmemb, size), NULL-1: reap all, otherwise free(ptr)
+ * @param nmemb number of elements of size to allocate
+ * @param size  size if each element
+ */
 void *
 heap_and_reap(void *ptr, size_t nmemb, size_t size)
 {
@@ -38,21 +41,24 @@ heap_and_reap(void *ptr, size_t nmemb, size_t size)
       tmp->requested = nmemb * size;
       tmp->ptr = result;
       tmp->prev = memalloc;
-      tmp->next = NULL;
-      if (memalloc)
+      tmp->next = memalloc ? memalloc->next : NULL;
+      if (memalloc) {
+        if (memalloc->next)
+          memalloc->next->prev = tmp;
         memalloc->next = tmp;
+      }
       else
         memalloc = tmp;
       if (heap_debug)
-        fprintf(stderr, "heap req %08lx alloc %08lx @ %p\n", tmp->requested, tmp->allocated, tmp);
+        fprintf(stderr, "heap %p req %08lx alloc %08lx @ %p track %p next %p\n", memalloc, tmp->requested, tmp->allocated, tmp->ptr, tmp, memalloc->next);
     }
   }
   else { // free allocation
     struct mem_track *p = memalloc;
     while (p) {
+      if(heap_debug)
+        fprintf(stderr, "%sheap %p free %08lx @ %p track %p next %p\n", (p->ptr != ptr ? "  " : ""), memalloc, p->requested, p->ptr, p, p->next);
       if (ptr == NULL-1 || p->ptr == ptr) { // free all or a specific allocation
-        if (heap_debug)
-          fprintf(stderr, "heap free %08lx @ %p\n", p->allocated, p);
         tmp = p->next;
         if (p->prev)
           p->prev->next = p->next;