Fix memory leaks and mistypes
[tedtools.git] / tmalloc.c
index d6c0b76..c03a7ff 100644 (file)
--- a/tmalloc.c
+++ b/tmalloc.c
@@ -161,6 +161,25 @@ freeMemoryContext(MemoryContext *cntx) {
        }
 }
 
+void
+resetMemoryContext(MemoryContext *cntx) {
+       MemoryChunk *chunk, *chunkptr;
+
+       while( cntx ) {
+               chunkptr = cntx->chunk;
+               chunkptr->freesize = chunkptr->size;
+               chunkptr = chunkptr->next;
+               cntx->chunk->next = NULL;
+
+               while( chunkptr ) {
+                       chunk=chunkptr->next;
+                       tfree(chunkptr);
+                       chunkptr=chunk;
+               }
+               cntx=cntx->child;
+       }
+}
+
 void*   
 mcalloc(MemoryContext *cntx, size_t size) {
        MemoryChunk     *chunk = cntx->chunk;
@@ -188,10 +207,10 @@ mcalloc(MemoryContext *cntx, size_t size) {
                chunk = newchunk;
        }
 
-       chunk->freesize -= size;
-       alloc = (MCAllocatedSpace*)( chunk->data + chunk->freesize );
+       alloc = (MCAllocatedSpace*)( chunk->data + chunk->size - chunk->freesize );
        alloc->size = size; 
        alloc->cntx = cntx;
+       chunk->freesize -= size;
  
        if ( cntx->flags & MC_DEBUG ) {
                *(u_int32_t*)((char*)alloc + alloc->size - sizeof(u_int32_t) ) = MCMAGICKNUMBER;
@@ -223,7 +242,8 @@ mcrealloc(void * ptr, size_t size) {
                realsize = alloc->size - MCASHDRSZ;
 
        if ( size > realsize ) {
-               if ( (char*)alloc == alloc->cntx->chunk->data + alloc->cntx->chunk->freesize && 
+               MemoryChunk *chunk = alloc->cntx->chunk;
+               if ( (char*)alloc == chunk->data + chunk->size - chunk->freesize - alloc->size &&
                                PTRALIGN(size)-realsize <= alloc->cntx->chunk->freesize ) {
                        /* just enlarge */
                        alloc->cntx->chunk->freesize -= PTRALIGN(size)-realsize;
@@ -248,6 +268,7 @@ mcrealloc(void * ptr, size_t size) {
 void    
 mcfree(void * ptr) {
        MCAllocatedSpace        *alloc = (MCAllocatedSpace*)( (char*)ptr - MCASHDRSZ );
+       MemoryChunk *chunk;
 
        if ( ptr==NULL )
                tlog(TL_CRIT|TL_EXIT, "mcfree: free null pointer");
@@ -255,7 +276,8 @@ mcfree(void * ptr) {
        if ( alloc->cntx->flags & MC_DEBUG ) 
                tassert(  *(u_int32_t*)((char*)alloc + alloc->size - sizeof(u_int32_t) ) == MCMAGICKNUMBER );
 
-       if ( (char*)alloc == alloc->cntx->chunk->data + alloc->cntx->chunk->freesize ) /* last allocated value */
+       chunk = alloc->cntx->chunk;
+       if ( (char*)alloc == chunk->data + chunk->size - chunk->freesize - alloc->size ) /* last allocated value */
                alloc->cntx->chunk->freesize+=alloc->size;
 
        alloc->cntx=NULL;