www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/09/01/23:32:17

Sender: nate AT cartsys DOT com
Message-ID: <35ECBAC4.32B42BFF@cartsys.com>
Date: Tue, 01 Sep 1998 20:25:56 -0700
From: Nate Eldredge <nate AT cartsys DOT com>
MIME-Version: 1.0
To: sl AT psycode DOT com DOT REMOVE_THIS
CC: djgpp AT delorie DOT com
Subject: Re: Remaining memory under OS/2 question
References: <Pine DOT SUN DOT 3 DOT 91 DOT 980831121628 DOT 22974W-100000 AT is> <35eb49be DOT 27826391 AT news> <iCdMCj1ZQ5j2-pn2-qwUsZjpOrKmU AT portC29 DOT Generation DOT NET>

sl AT psycode DOT com DOT REMOVE_THIS wrote:
> 
> On Tue, 1 Sep 1998 01:14:05, fesenko AT pacific DOT net DOT sg (Victor) wrote:
> 
> > On Mon, 31 Aug 1998 12:16:52 +0300 (IDT), Eli Zaretskii
> > <eliz AT is DOT elta DOT co DOT il> wrote:
> > But is there a way to find the amount of used memory then? That was
> > actually a real  purpose of checking remaining memory. I was looking
> > that  the remaining memory didn't go too low. If it did it meant I had
> > memory leaks somewhere.
> 
>         Same here .. There is no way to check for memory leaks .. :(

Not true.  A very simple way follows, though not tested:

---- file leakchk.c ---

#include <stdlib.h>
#include <sys/types.h>
#define NO_WRAP
#include "leakchk.h"

static size_t total_alloc = 0;

void *malloc_wrap(size_t s)
{
   size_t *t;
   if ((t = (size_t *)malloc(s + sizeof(size_t))) != NULL) 
     {
       total_alloc += s;
       *t = s;
       return (void *)(t + 1);
     }
   else return NULL;
}

void *realloc_wrap(void *p, size_t ns)
{
   /* Lazy implementation */
   free_wrap(p);
   return malloc_wrap(ns);
}

void free_wrap(void *p)
{
   size_t s;
   size_t *rp;
   rp = (size_t *)p;
   s = *(--rp);
   assert(s <= total_alloc);
   s -= total_alloc;
   free(p);
}

static void report_leak(void) __attribute__((destructor));

static void report_leak(void)
{
   if (total_alloc > 0)
      fprintf(stderr, "Leaked %d bytes\n", total_alloc);
}
------ end -----

------ file leakchk.h ---
#include <sys/types.h>

void *malloc_wrap(size_t);
void *realloc_wrap(void *, size_t);
void free_wrap(void *);

#ifndef NO_WRAP
#define malloc malloc_wrap
#define realloc realloc_wrap
#define free free_wrap
#endif
------- end -------

And just add #include "leakchk.h" in each file of your program.

Systems such as MSS give better diagnostics.  Yes, it can be done.
-- 

Nate Eldredge
nate AT cartsys DOT com

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019